JQuery each loop - do something with currently looped element - jquery-selectors

I have following .each jQuery loop.
$('.category').each(function(index) {
if( $('.category > span').parent().next('h2') ) {
// get currently looped element which follows the condition
}
});
How to get currently looped element through .each inside the if statement?

How to get currently looped element through .each inside the if
statement?
Use:
$(this) // represents current iterated element in wrapped set
Example:
$('.category').each(function(index) {
if( $('.category > span').parent().next('h2') ) {
$(this).css('color', 'red');
}
});
Note that you could also get DOM object instead of jQuery object by using this keyword.

$('.category').each(function(index) {
var that = $(this);
if( $('.category > span').parent().next('h2') ) {
// do something with `that`
}
});
Cached $(this) to avoid having to look it up every time you use it…

Related

how to compare a list of names in a table

My test scenario is to search for last name and expect whether all the names in the table are equal to the search value. I have a different function to search for the last name.
What i want now is to get all the names in the table and to test whether all the names have the same value. I want to use the below function in my page object and use it in the expect in the spec. How to do so?
I am confused how to use getText() and push them into an array and return the array so that i can use it in the expect
this.getAllBorrowerNamesInTable = function () {
element.all(by.binding('row.borrowerName')).then(function (borrowerNames){
});
};
Aside from using map(), you can approach it by simply calling getText() on the ElementArrayFinder - the result of element.all() call:
this.getAllBorrowerNamesInTable = function () {
return element.all(by.binding('row.borrowerName')).getText();
}
Then, you can assert the result to be equal to an array of strings:
expect(page.getAllBorrowerNamesInTable()).toEqual(["Borrower 1", "Borrower 2"]);
I am using the map() function to do the job:
this.getAllBorrowerNamesInTable = function () {
return element.all(by.binding('row.borrowerName')).map(function(elem) {
return elem.getText();
)};
}
You can use javascript 'push' function to add every borrower name and then we can return that array;
this.getAllBorrowerNamesInTable = function () {
var names = [];
element.all(by.binding('row.borrowerName')).then(function (borrowerNames){
borrowerNames.each(function(borrowerName) {
borrowerName.getText().then(function(name) {
names.push(name);
});
});
});
return names;
};

Trying to work with down() method from ExtJS 4.2.1

I am trying to find a specific element from my page using ExtJS 4 so I can do modifications on it.
I know its id so it should not be a problem BUT
-I tried Ext.getCmp('theId') and it just return me undefined
-I tried to use down('theId') method by passing through the view and I still get a nullresponse.
As I know the id of the element I tried again the two methods by setting manually the id and it didn't work neither.
Do these two methods not function?
How should I do?
Here is the concerned part of the code :
listeners: {
load: function(node, records, successful, eOpts) {
var ownertree = records.store.ownerTree;
var boundView = ownertree.dockedItems.items[1].view.id;
var generalId = boundView+'-record-';
// Add row stripping on leaf nodes when a node is expanded
//
// Adding the same feature to the whole tree instead of leaf nodes
// would not be much more complicated but it would require iterating
// the whole tree starting with the root node to build a list of
// all visible nodes. The same function would need to be called
// on expand, collapse, append, insert, remove and load events.
if (!node.tree.root.data.leaf) {
// Process each child node
node.tree.root.cascadeBy(function(currentChild) {
// Process only leaf
if (currentChild.data.leaf) {
var nodeId = ""+generalId+currentChild.internalId;
var index = currentChild.data.index;
if ((index % 2) == 0) {
// even node
currentChild.data.cls.replace('tree-odd-node', '')
currentChild.data.cls = 'tree-even-node';
} else {
// odd node
currentChild.data.cls.replace('tree-even-node', '')
currentChild.data.cls = 'tree-odd-node';
}
// Update CSS classes
currentChild.triggerUIUpdate();
console.log(nodeId);
console.log(ownertree.view.body);
console.log(Ext.getCmp(nodeId));
console.log(Ext.getCmp('treeview-1016-record-02001001'));
console.log(ownertree.view.body.down(nodeId));
console.log(ownertree.view.body.down('treeview-1016-record-02001001'));
}
});
}
}
You can see my console.log at the end.
Here is what they give me on the javascript console (in the right order):
treeview-1016-record-02001001
The precise id I am looking for. And I also try manually in case...
h {dom: table#treeview-1016-table.x-treeview-1016-table x-grid-table, el: h, id: "treeview-1016gridBody", $cache: Object, lastBox: Object…}
I checked every configs of this item and its dom and it is exactly the part of the dom I am looking for, which is the view containing my tree. The BIG parent
And then:
undefined
undefined
null
null
Here is the item I want to access:
<tr role="row" id="treeview-1016-record-02001001" ...>
And I checked there is no id duplication anywhere...
I asked someone else who told me these methods do not work. The problem is I need to access this item to modify its cls.
I would appreciate any idea.
You are looking for Ext.get(id). Ext.getCmp(id) is used for Ext.Components, and Ext.get(id) is used for Ext.dom.Elements. See the docs here: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext-method-get
Ok so finally I used the afteritemexpand listener. With the ids I get the elements I am looking for with your Ext.get(id) method kevhender :).
The reason is that the dom elements where not completely loaded when I used my load listener (it was just the store) so the Ext.get(id) method couldn't get the the element correctly. I first used afterlayout listener, that was correct but too often called and the access to the id was not so easy.
So, here is how I did finally :
listeners: {
load: function(node, records, successful, eOpts) {
var ownertree = records.store.ownerTree;
var boundView = ownertree.dockedItems.items[1].view.id;
var generalId = boundView+'-record-';
if (!node.tree.root.data.leaf) {
// Process each child node
node.tree.root.cascadeBy(function(currentChild) {
// Process only leaf
if (currentChild.data.leaf) {
var nodeId = ""+generalId+currentChild.internalId;
var index = currentChild.data.index;
if ( (index % 2) == 0 && ids.indexOf(nodeId) == -1 ) {
ids[indiceIds] = nodeId;
indiceIds++;
}
console.log(ids);
}
});
}
},
afteritemexpand: function( node, index, item, eOpts ){
/* This commented section below could replace the load but the load is done during store loading while afteritemexpand is done after expanding an item.
So, load listener makes saving time AND makes loading time constant. That is not the case if we just consider the commented section below because
the more you expand nodes, the more items it will have to get and so loading time is more and more important
*/
// var domLeaf = Ext.get(item.id).next();
// for ( var int = 0; int < node.childNodes.length; int++) {
// if (node.childNodes[int].data.leaf && (int % 2) == 0) {
// if (ids.indexOf(domLeaf.id) == -1) {
// ids[indiceIds] = domLeaf.id;
// indiceIds++;
// }
// }
// domLeaf = domLeaf.next();
// }
for ( var int = 0; int < ids.length; int++) {
domLeaf = Ext.get(ids[int]);
if (domLeaf != null) {
for ( var int2 = 0; int2 < domLeaf.dom.children.length; int2++) {
if (domLeaf.dom.children[int2].className.search('tree-even-node') == -1){
domLeaf.dom.children[int2].className += ' tree-even-node';
}
}
}
}
},
With ids an Array of the ids I need to set the class.
Thank you for the method.

Populate select in jqgrid filter toolbar

I've tried to populate a dropdownlist with values from my database. I've got the following code in my .js file:
function getDropdowndata() {
var sHTML;
var filter;
var url = "dropdown.json";
jQuery.getJSON(url, function (dddata) {
if (dddata.rows.length > 0) {
sHTML = "";
for (x = 0; x < dddata.rows.length; x++) {
sHTML += (dddata.rows[x].Type + ":" + dddata.rows[x].Type + ";");
}
filter = sHTML.substring(0, sHTML.length - 1);
}
});
return filter;
}
And in my Jqgrid list I've got the following:
editoptions: { value: ":All;" + getDropdowndata() }
The problem I've got with this code is that it seems that the function is being executed too early and because of that the dropdownlist contains nothing.
The reason for my assumption is that if I put an alert inside of the javascript function before the return, the dropdownlist is filled with the values and everything seems to work.
Any suggestions?
Instead of getting the data with a custom function using JSON, you might want to try using the built-in functionality for dynamic select fields (see documentation: select edittype ). All you do is specify a url where the code for the select element is generated.
colModel:[
{name:'colName',
editable:true,
edittype:'select',
formatter:'select',
editoptions:{dataUrl:'/path/to/generated/html/select'}
]
Then you just need to make sure that /path/to/generated/html/select returns all the right HTML code for a select element.

using jQuery selector with a dom element

I have a javascript function that receives a dom element as a parameter. In this function I am trying to get to the closest ancestor 'form'. I wanted to use:
function submit_form(obj)
{
var form1 = $(obj).closest("form");
alert (form1.id);
}
here obj is a dom element of submit type. I just don't seem to get it working.
Could someone please help?
You want
function submit_form(obj)
{
var form1 = $(obj).closest("form")[0];
alert (form1.id);
}
The result of jQuery selection/traversal functions always is an array, possibly with one element only, but still an array. Index into the array to get actual DOM elements.
However, you can do this without jQuery as long as obj is an input/select/textarea element.
function submit_form(obj)
{
var form1 = obj.form;
alert (form1.id);
}
For the sake of completeness, you could also stay within jQuery and do
function submit_form(obj)
{
var $form1 = $(obj).closest("form");
alert ( $form1.attr("id") );
}
function closest(obj, tagName) {
// Go up in the tree until you find the ancestor form
while (obj.parent !== null) {
if (obj.nodeType === 1) {
parent = obj.parentNode;
if (parent.tagName === tagName) {
return parent;
}
}
}
// If no form exists return null
if (obj.tagName !== tagName) {
return null;
}
}
Use it in this way
var closestForm = closest(obj, 'FORM')
form1 would be a jQuery object, so you can either use .attr("id"), or access the DOM element itself using [0].id:
var form1 = $(obj).closest("form");
alert(form1.attr("id"));
var form2 = $(obj).closest("form")[0];
alert(form2.id);

Can I use the > operator in a KRL query() selector?

I want to get a nested DIV tag using KRL query() but it complains with
ERROR Rules.pm a8x40 show_xfers Ruleset a8x40 failed: html.query error - Invalid specification ">div" in query: div.recent-transfer>div
Here's the HTML fragment (there are multiple in the file):
<div class='recent-transfer'>
<span>...</span>
<div> <!-- * * * -->
<div>...</div>
<div>...</div>
</div>
</div>
Here's my function:
recent = function() {
t = http:get(the_url).pick("$..content");
t.query("div.recent-transfer>div")
}
I want to select the DIV marked * * *. Do I need to chain several query() statements to get the DIV?
When I tried to reproduce your problem, I didn't get the same error. Instead, I would get a "NOT_FOUND_ERR: DOM Exception 8". In my case, it wasn't a problem with the selector at all; it was the fact that the return value of t.query was an array. If I wanted to use that in, say, a notify(), I had to get the 0th element out of the array and return that instead.
I don't know if that is the same problem you are having. But here's a sample ruleset that works for me:
ruleset a163x61 {
meta {
name "Selector test"
description <<
Testing the query() function
>>
author "Steve Nay"
logging on
}
dispatch {
}
global {
the_url = "http://students.cs.byu.edu/~snay2/content.html";
recent = function() {
t = http:get(the_url).pick("$..content");
// This produces an array.
text = t.query("div.recent-transfer>div");
// We want the text out of the element. Get the first element.
text[0];
// This won't work; throws a "NOT_FOUND_ERR: DOM Exception 8"
//text;
};
}
rule first_rule {
select when pageview ".*" setting ()
pre {
disp = recent();
}
notify("Content:", disp) with sticky=true;
}
}
"div.recent-transfer>div" is a valid query. There was a problem in the KNS causing intermittent failures.
Here's how the function is used, such that the returned array doesn't make problems:
rule add_content {
select when pageview ".*"
foreach recent() setting (item) {
append("div#main", item);
}
}