I have the following HTML code:
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value1</option>
</select>
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value2</option>
</select>
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value3</option>
</select>
Now before submitting the form I want to do the following
I believe I need to loop around but I am unable to find the initial syntax with which I can first grab all the values.
I know how to check if any value is selected when 'id' is given for a select element. But in this case I have the 'name' attribute which is an array.
I tried looking at different places but I haven't really come across a good solution. Probably I missed something.
Please let me know if any further information is required.
using map function
var selected = $('select[name="test[]"]').map(function(){
if ($(this).val())
return $(this).val();
}).get();
console.log(selected);
This isn't a complete solution, but may hopefully point you in the right direction (assuming your using jQuery)
The below code should loop through your selects (when they have the name='test[]'
) and add any values (that aren't blank) to the result array.
var results = [];
$("select[name='test[]']").each(function(){
var val = $(this).val();
if(val !== '') results.push(val);
});
console.log(results);
Demo: http://jsfiddle.net/W2Mam/
The following will let you iterate through select tags which has any selected value other than default "". You can adjust it to any other unwanted values etc.
$("select[name='test[]']").each(function(){
if($(this).val()!='')
{
//doStuff
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With