Reputation: 5294
given an array of radio buttons. how do I get an array of their values (including nulls) for example given.
// use jquery to display [Yes, null, null, No]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
true <input type="radio" name="one" value="Yes" checked>
false <input type="radio" name="one" value="No">
</p>
<p>
true <input type="radio" name="two" value="Yes">
false <input type="radio" name="two" value="No">
</p>
<p>
true <input type="radio" name="three" value="Yes" >
false <input type="radio" name="three" value="No" >
</p>
<p>
true <input type="radio" name="four" value="Yes">
false <input type="radio" name="four" value="No" checked >
</p>
how would I get [Yes, null, null No]
Upvotes: 3
Views: 3570
Reputation: 72289
1. You need to check each <p>
checked radio box length
2. if length is 0 then push NULL
to array otherwise push checked radio button value
Working snippet:-
$(document).ready(function(){
var radio_arr = [];
$('p').each(function(){
radio_arr.push($(this).find('input[type=radio]:checked').length ? $(this).find('input[type=radio]:checked').val() : 'NULL');
});
console.log(radio_arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
true <input type="radio" name="one" value="Yes" checked>
false <input type="radio" name="one" value="No">
</p>
<p>
true <input type="radio" name="two" value="Yes">
false <input type="radio" name="two" value="No">
</p>
<p>
true <input type="radio" name="three" value="Yes" >
false <input type="radio" name="three" value="No" >
</p>
<p>
true <input type="radio" name="three" value="Yes">
false <input type="radio" name="three" value="No" checked >
</p>
Upvotes: 3
Reputation: 3435
You can iterate over each individual input grouping and return the value of the one that has the checked
attribute:
var groups = ['one', 'two', 'three','four'];
var result = [];
groups.forEach(function(group,i){
result[i] = $('input[name='+group+']:checked').attr('value')
});
console.log(result); // will print ["Yes", undefined, undefined, "No"]
Here's a working example. Your HTML currently has the third and 4th groups both named "three" so I changed the last one to "four" to better match what you were looking to get as a result.
If you REALLY want null as the response, just add a conditional to return null
if the value === undefined
, but seems useless
Upvotes: 0