0

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;
        });
    });
}
3
  • For sure your name='+names... needs double quotes should read 'input:radio[name="'+names[i]+'"]') Commented Jul 17, 2015 at 19:33
  • In the second .each'-loop you use 'i' as index-variable ... use something else. Commented Jul 17, 2015 at 19:38
  • The reason is not the quotes. Because I change to 'input:radio[name='+names[0]+']' it works Commented Jul 17, 2015 at 19:38

3 Answers 3

1

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

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

Comments

0

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;
        });
    });
}

1 Comment

will still fail due to no closure for i
0

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;
        });
    });
});

2 Comments

if quotes are a problem (which they aren't), why are they not a problem in your second example?
Sorry, I forgot to add them in there. They are there now. I haven't tested the code as I should have before I answered, that's just what I noticed.

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.