Jquery length of matched query - javascript

How would I write both of these without using .each() and only using JQuery Selectors?
var xxxx = 0;
$('.clonedInput').each(function(index) {
if($(this).children().filter(':checked').length == 2)
xxxx++;
});
var num_normal_foods = 0;
$('[id^="amount_"]').each(function(index) {
if($(this).val() == '30.00')
num_normal_foods++;
});

Lets take this one step at a time.
You started with:
var xxxx = 0;
$('.clonedInput').each(function(index) {
if($(this).children().filter(':checked').length == 2)
xxxx++;
});
To me this looks like you're simply trying to filter a collection of .clonedInput elements and find out how many match the filter:
var xxxx;
function hasTwoCheckedChildren(i) {
return $(this).children(':checked').length == 2;
}
xxxx = $('.clonedInput').filter(hasTwoCheckedChildren).length;
Followed by:
var num_normal_foods = 0;
$('[id^="amount_"]').each(function(index) {
if($(this).val() == '30.00')
num_normal_foods++;
});
Again, this looks like a filtering function to me:
var num_normal_foods;
function valueIsThirty(i) {
return +$(this).val() === 30;
}
num_normal_foods = $('[id^="amount_"]').filter(valueIsThirty).length;
In the end, what matters is that the code does what you intend it to do. If the code you wrote with .each does what you want it to, then there's no need to change it. Behind-the-scenes filter uses each anyway.

jQuery selections have a .length property:
var len = $('.clonedInput :checked').length;
var len2 = $('[id^="amount_"][value="30.00"]').length;
the first query returns all of the checked children of any .clonedInput class, then counts them.
the second query finds all of the id's that begin with amount_ and have a value of "30.00". (property queries can be chained like that [][])
EDIT: to satisfy #Blazemonger
to get the value of any type of element (value works on some), use this:
var len2 = $('[id^="amount_"]').filter(function() {
return $(this).val() == "30.00";
}).length;
Double EDIT because i'm useless
var len = $('.clonedInput').filter(function(){
return $(this).children(':checked').length == 2;
}).length;

Related

Javascript loop doesn't work in meteor

This should work but its not. What am I doing wrong? I want to output "selected" to tags I have on a meteor page
Template.editor.onRendered( function() {
var cats = ["Comedy","Action","Self Help"];
var arrayLength = cats.length;
for (var i = 0; i < arrayLength; i++) {
if(cats[i].indexOf(getDocument.category) != -1){
//found
var id = cats[i].trim().toLowerCase();
$("body").find("#"+id).attr("selected=selected");
console.log(id);
} else {
console.log(getDocument.category)
}
}
}
also
getDocument.category = ["Action", "Comedy"]
Maybe change
$("body").find("#"+id).attr("selected=selected");
with
$("body").find("#"+id).attr("selected","selected");
Edit:
if(cats[i].indexOf(getDocument.category) != -1){
I think you have here a wrong direction
try this instead:
if(getDocument.category.indexOf(cats[i]) != -1){
If I do not mistakenly understand what you asking for, you are trying to find the elements of 'cats' array if exist in the getDocument.category. If so, the above approach is wrong. Take a look at this line:
if(cats[i].indexOf(getDocument.category) != -1){...}
the result of this if checking will always returning -1, the explanation is below:
cats[i] will return the element (with index i) of cats, so if i=0 the result will be "Comedy". Then, indexOf will be executed on it, "Comedy".indexOf() ,
to find the position of getDocument.category (which is an array).
That's means you are looking for an array inside a string? that's will not work.
Actually, we can check if an element exists in array with includes methods. So maybe the complete code will be looked like this:
Template.editor.onRendered(function() {
var cats = ["Comedy", "Action", "Self Help"];
var arrayLength = cats.length;
for (var i = 0; i < arrayLength; i++) {
if (getDocument.category.includes(cats[0])) {
//found
var id = cats[i].trim().toLowerCase();
$("body").find("#" + id).attr("selected=selected");
console.log(id);
} else {
console.log(getDocument.category)
}
}
})
Hope this will help, thanks
You need to change a line to set selected attribute
$("body").find("#"+id).attr("selected","selected");
Or try the following:
$(document).find("#"+id).attr("selected","selected");

How can I skip a specific Index in an array in a for loop javascript

Suppose I had a function that is pulling in values from somewhere and storing those values into an array.
function getSport(ply) {
some code here... //function gets values that I need for array later
}
var sports1 = getSport(playerChoice);
var sports2 = getSport(playerChoice);
var sports3 = getSport(playerChoice);
var sports4 = getSport(playerChoice);
var sportsArry = [sports1, sports2, sports3, sports4];
Now I would like to use a for loop to loop the elements, the problem, however, is the first index (index 0) will always be true. I want to skip index 0. How do I do that? Further I want to replace index 0 with something else. Let me show you
for (var i = 0; i<sportsArry.length; i++){
if ( (sports1 == sportsArry[i]) ) {
sports1 = null; //I figured I should null it first?
sports1 = replaceValueFunc(playerChoice2);
}
}
Well you can see the problem I would have. Index 0 is true.
Let me show you what would work, although it requires alot of or operators.
if ( (sports1 == sportsArry[1]) || (sports1 == sportsArry[2]) || (sports1 == sportsArry[3] ) {
...
}
^^ That is one way to skip index 0, what would be another better looking way?
I want to skip index 0. How do I do that? Further I want to replace
index 0 with something else.
Just start the loop from 1 instead of 0
sportsArr[0] = "Something else"; // set the first element to something else
for(var i = 1; i < sportsArr.length; i++){
// do something
}

JQuery for loop

I need to Loop in JQuery from 0 to variable-value(dynamically entered by user).How can i achieve this?
Now i am doing it by using simple For loop like this.
for( i=1; i<=fetch; i++) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Thanks.
You could loop an empty array:
$.each(new Array(fetch), function(i) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
});
If you do this alot you can even fake-patch jQuery.each to take numbers:
(function($) {
var _each = $.each;
$.each = function() {
var args = $.makeArray(arguments);
if ( args.length == 2 && typeof args[0] == 'number') {
return _each.call(this, new Array(args[0]), args[1]);
}
return _each.call(this, args);
};
}(jQuery));​
$.each(fetch, function(i) {
// loop
});
jQuery.each does have some great features, like the different return values inside the callback. But for a simple loop I find it much more convenient (and less overhead) to do something like:
while(fetch--) {
// loop
}​
To loop between two values you should use a regular Javascript loop. The jQuery each methods are used when looping through a collection of elements or an array.
To loop from zero, you should initialise the loop variable to zero, not one. To loop from zero to the specified value, you use the <= for the comparison, but to loop from zero and the number of items as specified (i.e. from 0 to value-1), you use the < operator.
for (i = 0; i < fetch; i++) {
$('body').append($('<input/>', { type: 'text' }));
}
You mean Javascript loop.
From W3Schools:
for (var variable = startvalue; variable < endvalue; variable = variable + increment)
{
//code to be executed
}
To get the value from user and run the code you can use the following prompt.
var x=prompt("Enter the value",0);
for(i=0;i<x;i++)
{
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Hope this helps.
Thanks
If you want it the full jQuery way then use that new plugin jQuery-timing. It provides inline-loops in your jQuery line:
$('body').repeat().append('<input>').until(fetch);
Nice, eh?

Find HTML based on partial attribute

Is there a way with javascript (particularly jQuery) to find an element based on a partial attribute name?
I am not looking for any of the selectors that find partial attribute values as referenced in these links:
starts with [name^="value"]
contains prefix [name|="value"]
contains [name*="value"]
contains word [name~="value"]
ends with [name$="value"]
equals [name="value"]
not equal [name!="value"]
starts with [name^="value"]
but more something along the lines of
<div data-api-src="some value"></div>
<div data-api-myattr="foobar"></div>
and
$("[^data-api]").doSomething()
to find any element that has an attribute that starts with "data-api".
This uses .filter() to limit the candidates to those that has data-api-* attributes. Probably not the most efficient approach, but usable if you can first narrow down the search with a relevant selector.
$("div").filter(function() {
var attrs = this.attributes;
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].nodeName.indexOf('data-api-') === 0) return true;
};
return false;
}).css('color', 'red');
Demo: http://jsfiddle.net/r3yPZ/2/
This can also be written as a selector. Here's my novice attempt:
$.expr[':'].hasAttrWithPrefix = function(obj, idx, meta, stack) {
for (var i = 0; i < obj.attributes.length; i++) {
if (obj.attributes[i].nodeName.indexOf(meta[3]) === 0) return true;
};
return false;
};
Usage:
$('div:hasAttrWithPrefix(data-api-)').css('color', 'red');
Demo: http://jsfiddle.net/SuSpe/3/
This selector should work for pre-1.8 versions of jQuery. For 1.8 and beyond, some changes may be required. Here's an attempt at a 1.8-compliant version:
$.expr[':'].hasAttrWithPrefix = $.expr.createPseudo(function(prefix) {
return function(obj) {
for (var i = 0; i < obj.attributes.length; i++) {
if (obj.attributes[i].nodeName.indexOf(prefix) === 0) return true;
};
return false;
};
});
Demo: http://jsfiddle.net/SuSpe/2/
For a more generic solution, here's a selector that takes a regex pattern and selects elements with attributes that match that pattern:
$.expr[':'].hasAttr = $.expr.createPseudo(function(regex) {
var re = new RegExp(regex);
return function(obj) {
var attrs = obj.attributes
for (var i = 0; i < attrs.length; i++) {
if (re.test(attrs[i].nodeName)) return true;
};
return false;
};
});
For your example, something like this should work:
$('div:hasAttr(^data-api-.+$)').css('color', 'red');
Demo: http://jsfiddle.net/Jg5qH/1/
Not sure what it is you're looking for, but just spent a few minutes writing this:
$.fn.filterData = function(set) {
var elems=$([]);
this.each(function(i,e) {
$.each( $(e).data(), function(j,f) {
if (j.substring(0, set.length) == set) {
elems = elems.add($(e));
}
});
});
return elems;
}
To be used like :
$('div').filterData('api').css('color', 'red');
And will match any elements with a data attribute like data-api-*, and you can extend and modify it to include more options etc. but of right now it only searches for data attributes, and only matches 'starts with', but at least it's simple to use ?
FIDDLE

Does JavaScript or jQuery have a function similar to Excel's VLOOKUP?

Do JavaScript or jQuery have a function that returns the element of an array whose index equal to the position of a given value in another array? (I could write my own, but I don't want to reinvent the wheel.)
Something like:
function vlookup(theElement, array1, array2) {
$.each(array1, function(index, element) {
if (element === theElement)
return array2[index];
});
return null;
}
But, um... in the standard library.
Something like this perhaps?
Array.prototype.vlookup = function(needle,index,exactmatch){
index = index || 0;
exactmatch = exactmatch || false;
for (var i = 0; i < this.length; i++){
var row = this[i];
if ((exactmatch && row[0]===needle) || row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1)
return (index < row.length ? row[index] : row);
}
return null;
}
Then you can use it against a double array, like so
Depending your purpose, you can modify the indexOf to make both strings lowercase first so the comparison doesn't fail with "foo" vs "FOO". Note also that if index exceeds the row's length, the entire row is returned (this can be changed to the first element (or whatever) easily by modifying the : row); portion.

Categories