Get only unique names from more items

I dynamically rendered HTML that lists an indefinite number of radio buttons whose names are some identifiers in the database.

I need to collect all the unique names of the radio stations.

Here is an example:

<input name="721" type="radio" value="A" /> <input name="721" type="radio" value="I" /> <input name="722" type="radio" value="A" /> <input name="722" type="radio" value="I" /> <input name="723" type="radio" value="A" /> <input name="723" type="radio" value="I" /> 

Checking radio stations is NOT required, so using the selected or verified attribute will not work.

Is there an elegant way to get all the unique radio station names using jQuery? I know that I can just skip all the radio stations, but I hope jQuery has a more elegant way to do this?

+4
source share
8 answers

jsBin demo

 var arr = []; $.each( $('input:radio'), function(){ var myname= this.name; if( $.inArray( myname, arr ) < 0 ){ arr.push(myname); } }); alert(arr); // 721,722,723 
+6
source
 var names = $('input[type=radio]').map(function() { return this.name }).get(); // create an array of names var unique = $.grep(names, function(v, i) { return $.inArray(v, names) === i }); // filter unique values 

http://jsfiddle.net/WnHvz/

+1
source
 $('input:radio').each(function(){ // do something }); 
0
source

FYI - published html has no unique names. There are two of each ... but here is how you can get them:

 $('input[type="radio"]').each(function() { alert($(this).attr('name')); });​ 
0
source

if you want to print those names before each radio , then use it:

 $('input[type="radio"]').each(function() { $(this).before($(this).attr('name')); });​ 

try the script: http://jsfiddle.net/teLjg/

0
source

To get unique names, you can use map () to build an array of all the names, and then concatenate $. grep () with $. inArray () to remove duplicates.

Sort of:

 var allNames = $("input[type=radio]").map(function() { return $(this).attr("name"); }).get(); var uniqueNames = $.grep(allNames, function(name, index) { return $.inArray(name, allNames) == index; }); 
0
source

Just try to loop and get all the names and store them in an array ... then, using the filter method, you can filter unique values ​​....

let's say

 var array=[your array values]; var unique_val = array.filter(function(value,iter,array){ return iter == array.indexOf(value); }); 

It might work ...

0
source

I think you are so fast and love jQuery, yes. this can help you, in case of 2 switches, http://jsfiddle.net/BTcrR/ check it out

 $(function() { // list of var rediobuttonsName = new Array(); // you can use :odd | :even $('input[type="radio"]').not(':odd').map(function(n, elem) { rediobuttonsName.push(elem.name); // or you can use the context of object this // this.name }); alert(rediobuttonsName); });​ 

or you can drive .not (": odd") and check the array if it has a name value .;)

-1
source

All Articles