Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select or get all values from Select drop down array using Jquery or JavaScript

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

  1. Check if any of the above is selected.
  2. If selected retrieve its value.

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.

like image 927
Deep Avatar asked Feb 18 '14 13:02

Deep


3 Answers

using map function

var selected = $('select[name="test[]"]').map(function(){
    if ($(this).val())
        return $(this).val();
}).get();

console.log(selected);
like image 175
Pham Avatar answered Nov 17 '22 00:11

Pham


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/

like image 30
Carl Avatar answered Nov 17 '22 01:11

Carl


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
    }
});
like image 1
Cpt Balu Avatar answered Nov 17 '22 01:11

Cpt Balu