jQuery: Unable to get the values of select boxes with the same name

I have a set of select boxes with the same name. I want to get the selected values of those select boxes through jQuery and make an array.

function submitboxes(){
var manufCountry = $('input[name=manufacturerCountry]').map(function(){
    return this.value;
    }).get();
    
console.log(manufCountry);
}
<form><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="manufacturerCountry[]" id="" class="form-control customSelect"><option value="1">A</option><option value="2">B</option></select>

<select name="manufacturerCountry[]" id="" class="form-control customSelect"><option value="3">C</option><option value="4">D</option></select>
<button type="button" onclick="submitboxes();">Submit</button>
</form>

However, in the console, I see

[]

Upvotes: 0

Views: 45

Answers (1)

empiric
empiric

Reputation: 7878

Your array is always empty because your selector is not matching your HTML:

$('input[name=manufacturerCountry]') will search for an input with the name attribute equal to manufacturerCountry.

Your HTML however contains a select element with the name manufacturerCountry[]. So when changing your selector to

$('select[name^=manufacturerCountry')

your code will work properly.


Example

Note: I've changed the event handling to remove the onclick attribute


Reference:

jQuery attribute selector

Upvotes: 1

Related Questions