Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each loop through only groups not for each radio button?

Why does this selector goes through each radio button instead just to loop as much as there is different groups? http://jsfiddle.net/nardev/3AsCm/2/

This is how i test it:

<input type="radio" name="group1" />
<input type="radio" name="group1" />
<input type="radio" name="group1" />

<input type="radio" name="group2" />
<input type="radio" name="group2" />
<input type="radio" name="group2" />

js:

$('input[name^="group"]').each(function(index){
    console.log(index +": "+$(this).attr("name"));
    $(".h").append(index +": "+$(this).attr("name") +"<br />");
});

1 Answers

Your selector selects all input elements withe name attribute starting with group, it doesn't filter out unique names

If you want to print only different group names then

var group = {};
$('input[name^="group"]').each(function (index) {
    var name = this.name;
    if (!group[name]) {
        group[name] = true;
        $(".h").append(index + ": " + name + "<br />");
    }
});

Demo: Fiddle

like image 180
Arun P Johny Avatar answered Mar 24 '26 02:03

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!