Alan Yu
Alan Yu

Reputation: 1542

Using loop in jquery not work

I want to use for loop to create jquery function, but when I add the array parameter in the string, it didn't work. Any suggestion?

var ids=["width_uncheck","thickness_uncheck"];
var names=['width','thickness'];
for(i=0;i<2;i++){
    $("#"+ids[i] ).click(function() {
        $('input:radio[name='+names[i]+']').each(function(i) {
            this.checked = false;
        });
    });
}

Upvotes: 0

Views: 31

Answers (3)

charlietfl
charlietfl

Reputation: 171679

You can't do this because i has changed to it's maximum at the time the click event occurs.

You need to use a javascript closure which you can easily do with $.each

$.each(ids, function(i, id){
   $("#"+id ).click(function() {
        // no need for `each`, just use `prop()`
        $('input:radio[name='+names[i]+']').prop('checked',false);
    });
});

The difference here is that i is an argument of the function and therefore won't change it's value within the function the way it will in for loop

Upvotes: 1

ijsnow
ijsnow

Reputation: 162

You are missing the quotes for the name in the selector.

You could also just use the jquery each function without an element for your array.

$.each(ids, function (i, value) {
    var ids=["width_uncheck","thickness_uncheck"];
    var names=['width','thickness'];

    $("#"+ids[i] ).click(function() {
        $('input:radio[name="'+names[i]+'"]').each(function(i) {
            this.checked = false;
        });
    });
});

Upvotes: 0

Bhavin Solanki
Bhavin Solanki

Reputation: 4818

You have error with selector with radio name you need to add quote sign there You need to use $('input:radio[name="'+names[i]+'"]')

For ie

var ids=["width_uncheck","thickness_uncheck"];
var names=['width','thickness'];
for(var i=0;i<2;i++){
    $("#"+ids[i] ).click(function() {
        $('input:radio[name="'+names[i]+'"]').each(function(i) {
            this.checked = false;
        });
    });
}

Upvotes: 0

Related Questions