Loop Elements in JQuery - javascript

I am trying to run a loop over a few elements in JQuery. Before anyone says it, I do not need .each(). I am trying to run through the elements as a genuine loop- once a successful iteration runs, the loop will break and prevent the same action being done on other elements. I looked briefly at the straight JavaScript version, with the .getElement... methods, but it is my understanding that this won't satisfy my other requirement- the list of elements to be iterated over is created via a partial-string JQuery identifier:
rows = $('tr[id^="am_assetRow_' + parentAsset.replace(/ /, "_") + '_' + type + '"]');
Does anyone know of anything that might help me get this working?
EDIT: Just a bit more information on the application: I am checking to see if a value can be inserted into an existing row of a table, and if not, creating a new row and inserting it there. Thus, I need the loop to exit if a suitable fit is found, and after the loop terminates, I need to know whether it terminated in success (placing the value) or failure (no available locations- time to create a new row).

In jquery, if you want a $.each() loop to end immediately, just return false from the function call.

Do do a normal loop without using each() but still using jquery to select the items based on partial string etc...
rows = $('tr[id^="am_assetRow_' + parentAsset.replace(/ /, "_") + '_' + type + '"]');
for (var i = 0; i < rows.length; ++i) {
rows[i]; // The raw element at this index.
$(rows[i]); // jquery collection for this one element.
if (someCondition) {
break; // Break the loop early.
}
}

Related

Iterating over jQuery selector with variable, using closures

[First time on stackoverflow.] I am trying to dynamically add html buttons to my page and then give them a javascript function to run when they are clicked, using jQuery's click. I want to have one button for each element in an array, so I used a for loop. My code looks like this (simplified)
for (var i = 0; i < results.length; i++) {
$("#" + place[i].place_id).click(function(){console.log("Test");})
$("#" + place[i].place_id).click();
}
(I inject buttons with the right id's in the same loop.) This code, when run, console logs "Test" the right number of times, but afterwards, only the last button responds "Test" when clicked. (This situation is a little absurd.) So, I think the event handler ends up using only the final value of i to assign the event handler. I think the problem has to do with closures, but I am not sure how to make a closure out of a jQuery Selector (and in general am not familiar with them).
In contrast, as a hack solution, I "manually" wrote code like the below right below and outside the for loop, and it works as expected, in that clicking causes the console log.
$("#" + place[0].place_id).click(function(){console.log("Test"););
$("#" + place[1].place_id).click(function(){console.log("Test");});
etc.
(Of course, this all occurs within a larger context - specifically a Google Maps Places API call's callback.)
First, am I understanding the problem correctly? Second, what would work? Should I take a different approach altogether, like use a .each()?
(I later would want to display a property of place[i] when clicked, which I would think would need another callback
My final hack code looks like this:
$("#" + place[0].place_id).click(function(){google.maps.event.trigger(placeMarkers[0], "click"); repeated 20 times
To do this, you can simply create a self executing function inside the for loop, like this:
for (var i = 0; i < results.length; i++) {
(function(index) {
$("#" + place[index].place_id).click(function() {
//Do something with place[index] here
});
})(i);
}

jQuery for loops not running function

I'm trying to make a loop in jQuery that finds all 'img' elements and places a caption below them, according to the value of the element's 'caption' attribute. Whenever I run the loop below, I am left with no captions under any of the images.
for (var i = 0; i < $('.myimage').length; i++) {
$('.myimage')[i].after('<h6>' + $('.myimage').attr('caption') + '</h6>');
};
However, when I run this code
$('.myimage').after('<h6>TEST</h6>');
the word 'TEST' appears below all of the images. Therefore I know my html is correct, I have no typos, and the selector is working, I just cannot get the for loop to work... What have I done wrong?
$('.myimage')[i] returns a DOM element (not a jQuery object) so there is no after method. If you want to loop, simply use .each
$(".myimage").each(function() {
//this refers to each image
$(this).after('<h6>' + $(this).attr('caption') + '</h6>');
});
You can loop through the .myimage elements like this, using .after()'s callback function
$('.myimage').after(function(){
return '<h6>' + $(this).attr('caption') + '</h6>';
});
One minor note, don't make up your own attributes. use the custom data attribute instead, like data-caption="something".
jsFiddle example

Javascript taking too long to run

I have a script that is taking too long to run and that is causing me This error on ie : a script on this page is causing internet explorer to run slowly.
I have read other threads concerning this error and have learned that there is a way to by pass it by putting a time out after a certain number of iterations.
Can u help me apply a time out on the following function please ?
Basically each time i find a hidden imput of type submit or radio i want to remove and i have a lot of them . Please do not question why do i have a lots of hidden imputs. I did it bc i needed it just help me put a time out please so i wont have the JS error. Thank you
$('input:hidden').each(function(){
var name = $(this).attr('name');
if($("[name='"+name+"']").length >1){
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
}
});
One of the exemples i found : Bypassing IE's long-running script warning using setTimeout
You may want to add input to your jquery selector to filter out only input tags.
if($("input[name='"+name+"']").length >1){
Here's the same code optimised a bit without (yet) using setTimeout():
var $hidden = $('input:hidden'),
el;
for (var i = 0; i < $hidden.length; i++) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
}
Notice that now there is a maximum of three function calls per iteration, whereas the original code had up to ten function calls per iteration. There's no need for, say, $(this).attr('type') (two function calls) when you can just say this.type (no function calls).
Also, the .remove() only happens if three conditions are true, the two type tests and check for other elements of the same name. Do the type tests first, because they're quick, and only bother doing the slow check for other elements if the type part passes. (JS's && doesn't evaluate the right-hand operand if the left-hand one is falsy.)
Or with setTimeout():
var $hidden = $('input:hidden'),
i = 0,
el;
function doNext() {
if (i < $hidden.length) {
el = $hidden[i];
if(el.type!=='radio' && el.type!=='submit'
&& $("[name='" + el.name + "']").length >1) {
$(el).remove();
}
i++;
setTimeout(doNext, 0);
}
}
doNext();
You could improve either version by changing $("[name='" + el.name + "']") to specify a specific element type, e.g., if you are only doing inputs use $("input[name='" + el.name + "']"). Also you could limit by some container, e.g., if those inputs are all in a form or something.
It looks like the example you cited is exactly what you need. I think if you take your code and replace the while loop in the example (keep the if statement for checking the batch size), you're basically done. You just need the jQuery version of breaking out of a loop.
To risk stating the obvious; traversing through the DOM looking for matches to these CSS selectors is what's making your code slow. You can cut down the amount of work it's doing with a few simple tricks:
Are these fields inside a specific element? If so you can narrow the search by including that element in the selector.
e.g:
$('#container input:hidden').each(function(){
...
You can also narrow the number of fields that are checked for the name attribute
e.g:
if($("#container input[name='"+name+"']").length >1){
I'm also unclear why you're searching again with $("[name='"+name+"']").length >1once you've found the hidden element. You didn't explain that requirement. If you don't need that then you'll speed this up hugely by taking it out.
$('#container input:hidden').each(function(){
var name = $(this).attr('name');
if($(this).attr('type')!=='radio' && $(this).attr('type')!=='submit'){
$(this).remove();
}
});
If you do need it, and I'd be curious to know why, but the best approach might be to restructure the code so that it only checks the number of inputs for a given name once, and removes them all in one go.
Try this:
$("[type=hidden]").remove(); // at the place of each loop
It will take a short time to delete all hidden fields.
I hope it will help.
JSFiddle example

determining if a field exists on a form

I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}

JavaScript, loop all selects?

Well im new to javascript but why does this not work, all i want to do is to get a list of all selects on the page.
var elements = document.getElementsByTagName("select");
alert("there are " + elements.length + " select's");
for (i = 0; i < elements.length; i++)
{
alert(elements[i].getAttribute('Id'));
}
Edit: the error is that it does not find any selects at all, elements.length is allways zero!
You'r saying that elements.length is always returning 0 for you, this could be because:
You are running the JS code in the beginning of your page, thus the DOM is not fully available yet
Try using .id instead of of getAttribute('Id').
I guess the part of getting id attribute doesn't work for you. Probably it's because you typed there "Id" instead of "id".
The usual cause for getElementsByTagName returning zero results in a document with matching elements is that it is being run before the elements appear in the document (usually in the section and not inside a function that is called onload or onDomReady).
Move the element to just before the (END of body!) tag, or use an event handler that fires after the HTML has all been processed.
Well, as far as I can see is that perhaps the selects on your page don't have Id's (the alerts in the loop show null)

Categories