Kuru Kuru - 18 days ago 5
HTML Question

jquey-Get Value from different select tag with same name

I was trying to get the value from different select tag with the same name using jQuery.

The following is the HTML

<div class="row">
<div class="col-md-3">
<h1><i class="fa fa-glass" aria-hidden="true"></i></h1>
<select class="form-control SelectWine" id="SelectWine" name="SelectWine[]">
<option value="1">Red</option> <option value="2">Green</option> <option value="3">White</option> </select>
</div>
<div class="col-md-3">
<h1><i class="fa fa-glass" aria-hidden="true"></i></h1>
<select class="form-control SelectWine" id="SelectWine" name="SelectWine[]">
<option value="1">Red</option> <option value="2">Green</option> <option value="3">White</option> </select>
</div>

</div>


The following is how i am accessing in jquery

$('.SelectWine').each(function (index){
var wineId=[];
wineId.push($(this).val());
console.log('Wid',wineId[0]);
console.log('Wid',wineId[1]);
console.log('Wid',wineId[2]);
});


I am getting console log as following

Wid 1
Wid undefined
Wid undefined
Wid 3
Wid undefined
Wid undefined


I'm guessing each time it's overriding the value. But i need to store the values from each select tag in to one array.

Note: the first select tag is in the default(index 1) and second one i selected the third option(index 3).

This code is to get the users input for 2 or 3 differnt product and store it into the cookie for further use, but first i need to store it as array then i am able to store as json array in the cookie.



I tried accessing through the name of the element but it's only responding for accessing using the id.


I was trying for hours, can't figure out a way. your help will be great !!

Answer

You need to declare the array outside the loop, otherwise you are creating a new array in each iteration and don't have access to it outside of the each callback due to scope.

var wineId=[];
$('.SelectWine').each(function (index){
       //now each iteration will push to same array
       ....

When you need to generate an array like this you can use map()

var windeId = $('.SelectWine').map(function(){
    return this.value;
}).get();