1

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;
}
2
  • Watch out about the scope of the current variable, if everything else fails, declare it empty at the top of your get_role function Commented Aug 26, 2013 at 19:44
  • 3
    Try using a regular for loop rather than for..in for array-like collections. You may be getting more properties for elem than you expect. stackoverflow.com/questions/500504/… Commented Aug 26, 2013 at 19:48

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Or, you could instead iterate over the collection using an index loop rather than a for in loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.