jquery name selector not working in ie6 - javascript

var brands = document.getElementsByName("brand");
for(var brand in brands){
$("input[name='brand']").eq(brand).click(function(){
alert("hello22");
loadDataFN(1);
});
}
This code is not executing in ie6,
Any help would be appreciated.

The problem is likely that you are trying to use a for-in construct to iterate over a numeric array. This often won't give expected results. Use an incremental for loop instead:
var brands = document.getElementsByName("brand");
// Use an incremental for loop to iterate an array
for(var i=0; i<brands.length; i++){
$("input[name='brand']").eq(brands[i]).click(function(){
alert("hello22");
loadDataFN(1);
});
}
However,
after seeing the first part of your code, the loop appears unnecessary. You should only need the following, since you are assigning the same function to all brand inputs.
// These will return the same list of elements (as long as you don't have non-input elements named brand)
// though the jQuery version will return them as jQuery objects
// rather than plain DOM nodes
var brands = document.getElementsByName("brand");
$("input[name='brand']");
Therefore, the getElementsByName() and loop are not necessary.
$("input[name='brand']").click(function() {
alert("hello22");
loadDataFN(1);
});
for-in loops are used for iterating over the properties of an object, not over the elements of an array.

Why don't you write the code without jQuery if this doesn't work?
Something like this:
function getInputByName(name) {
var i, j = document.getElementsByTagName('input').length;
for(i=0;i<j;++i) { // You can also use getAttribute, but maybe it won't work in IE6
if(document.getElementsByTagName('input')[i].name === name) {
return document.getElementsByTagName('input')[i];
}
}
return null;
}
I don't know jQuery, but maybe you can do something like this:
$(getInputByName('brand')).eq(brand).click(function(){
alert("hello22");
loadDataFN(1);
});

Related

Removing and appending on wrapper in the same loop causes issues

I'm making a simple filtering function where I pass a sorted array into a function which is supposed to clear the wrapper and add the new ordered elements. My natural thought here is to do the removing and adding in the same loop, but I just can't get it to work and I can't really figure out why it wouldn't work.
Function that takes an array as argument. The sorted array is passed inside the function without any issues. The array is an Array.from(nodeList).
function removeAndAdd(sortedArray) {
for (let i = 0; i < allPosts.length; i++) {
const forumPost = allPosts[i]
forumPost.replaceWith(sortedArray[i])
}
}
NOTE: I've also tried (And alot of other stuff)
for (let i = 0; i < allPosts.length; i++) {
const forumPost = allPosts[i]
forumPost.remove()
wrapper.append(orderedArray[i])
}
My expectation is that with a single loop you should be able to clear the elements and at the same time att a new element. I don't want to use two different loops here.
Edit: I solved it by using remove() in an async function outside. I'd still love to learn technically why this didn't work.

Javascript recursion loop items to array

I am trying to make a small program that prompts a user to add items to a grocery list.
I read about using recursion to loop. I understand a while loop would probably be better suited for this task, but I ran into the same problems with the while loop and I wanted to try recursion. It just sounds like I know what I'm doing... "Yeh, I used recursion to enumerate the array while prompting validation from the user... hur hur hur"... but, I digress.
Here is the code:
function addToArray() {
var array = [];
array.push(prompt("Add items to array or 'q' to stop"));
if (array.pop() == 'q') {
document.write(array)
}
else {
addToArray();
}
}
addToArray();
If you'll notice, it loops like its supposed to but it is not adding items to an array. I have tried the array[i] = i technique as well but to no avail, the array remains empty. Also, why is it that by using a function with no args am I not running into too much recursion? Is it because of the conditional statement?
If you know what I'm doing wrong, try and hint towards the right answer rather than just blurting it out. I'd like to have that 'Aha' moment. I think this all helps us learn a bit better.
Thanks guys. (and gals)
You're creating a new array instead of passing it to the recursive call.
Do this instead.
DEMO: http://jsfiddle.net/kDtZn/
function addToArray(array) {
array.push(prompt("Add items to array or 'q' to stop"));
if (array[array.length-1] == 'q') {
array.pop();
document.write(array)
}
else {
addToArray(array);
}
}
addToArray([]);
Now you start with an empty array, and for each recursive call, it passes the same array forward.
Also, I changed it so that it doesn't use .pop() in the if() condition, otherwise you'll always end up with an empty array when it comes time to write it. (The .pop() method actually removes the last item.)
Finally, make sure you're not using document.write after the DOM is loaded. If so, you need to change it to use DOM manipulation methods instead.
You could take a different approach so that you don't need .pop() at all.
DEMO: http://jsfiddle.net/kDtZn/1/
function addToArray(array) {
var item = prompt("Add items to array or 'q' to stop");
if (item == 'q') {
document.body.textContent = array;
} else {
array.push(item);
addToArray(array);
}
}
addToArray([]);
The reason your while loop didn't work is very likely because of the original .pop() issue.
Your function recreates var array = [] on every loop/recursion. I am not sure if recursion is the right tool for the job in your case - it does not seems like it - but if you're starting out with JavaScript/development and just trying it out then you're fine.
While an 'infinite loop' is probably what you really want (as it would probably make the code simpler), you can do this with recursion by defaulting the array and passing it as an argument to the function. Like so...
function addToArray( array ) {
var array = array || [];
array.push(prompt( "Add items to array or 'q' to stop" ));
if ( array[array.length - 1] === 'q' ) {
document.write(array.slice( 0, -1 ))
} else {
addToArray( array );
}
}
addToArray();
There's two issues with the code as you presented. One, as pointed out earlier, you're redefining your array variable every time you call your function. Second, array.pop() alters your array, so when you get to the document.write call, you'd be printing an empty array anyways.

Undefined var in IE8 javascript/jQuery

I'm having a bit of an issue with IE8 and jQuery 1.9.1.
The target browser is IE8. I get an undefined variable when I try to alert the rolevalue var.
Here's the code:
function get_role(){
var test = document.getElementsByName("admin_role");
for(var elem in test){
if(test[elem].checked){
var rolevalue = test[elem].value;
$.post('<?php echo base_url(); ?>ajaxsc/getrole/',{role:rolevalue},function(result){
$('#roletest').html(result);
});
}
}
**alert('role = ' + rolevalue);**
return rolevalue;
}
The problem is that the for..in loop is iterating over some unwanted items.
If you using a for..in loop, you need to be aware of this; you may get the loop iterating over object properties that are part of the object prototype rather than actual elements that you want to iterator over.
What is happening is that it's hitting an property in the loop that is not a DOM element, and of course, that means it doesn't have a .value, so when you try to set the variable from .value, you get undefined.
To avoid this, you need to use the .hasOwnProperty() method to determine whether the loop is iterating a prototype method, and avoid them. You need to do something like this:
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
.....
}
}
Hope that helps.

Accessing the third level inside a Javascript object

I am trying to list out all the elements inside an array and as you can see Company has three levels, but I've only written the script to print the output until two levels. How do I access the third level? What should be the array that I should be using inside the third for loop?
What you're looking for is recursion.
Here is a fixed version of your fiddle: http://jsfiddle.net/jEmf9/
function generateEntity(obj) {
var html = [];
var name = obj.entity;
html.push('<li>');
html.push(name);
html.push('</li>');
var arrayName = name.replace(/\s/gi, '_');
if (obj[arrayName] == undefined) {
return html.join('');
}
var entity = obj[arrayName];
for (var i = 0; i < entity.length; i++) {
html.push('<ul>');
html.push(generateEntity(entity[i]));
html.push('</ul>');
}
return html.join('');
}
In your case you do not need a special technique for accessing the third level. You need to write a recursive tree walking function so that you can render a tree of any depth.
I've done a quick patch of your code here: http://jsfiddle.net/rtoal/xcEa9/6/
Once you get things working as you like, you can work on forming your html. Your repeated string concatenation using += is known to be extremely inefficient, but that is outside the scope of this question. :)

Javascript function: nothing executes after a for(x in y) loop?

I can't seem to find the answer to this anywhere...
I have a function that needs to set the bg color of two tables. Only the first table in the function is being affected. Is only one for loop allowed in a function? ...or is the 1st for loop maybe never exiting?
I can pretty much work around this by creating multiple functions but I really want to understand why this behaves the way it does!
Thanks!
Here is my simplified code:
function setColor()
{
//This works
var t1rows=document.getElementById("table1").getElementsByTagName("tr");
var x;
for (x in t1rows)
{
t1rows[x].style.backgroundColor='yellow';
}
//this one does not work
var t2rows=document.getElementById("table2").getElementsByTagName("tr");
var y;
for (y in t2rows)
{
t2rows[y].style.backgroundColor='yellow';
}
}
getElementsByTagName() returns a NodeList object, and for-in will iterate its properties which you don't want. You want to use a straight for loop:
for(var i=0; i < t2rows.length; i++) {
t2rows[i].style.backgroundColor='yellow';
}
You're not getting to the second loop because the first is failing when it tries to access a non-existent style property on one of the NodeList's members.

Categories