mcadamsjustin mcadamsjustin - 26 days ago 10
Javascript Question

Get array value based on different select boxes

I have two select boxes:

<select class="company">
<option value=''><strong>Name</strong></option>
<option value="Company A">Company A</option>
<option value="Company B">Company B</option>
</select>
<select class="product">
<option value=''><strong>Products</strong></option>
</select>


I need to get the location value from the array based on the two select box selections. It will be used in another function. Here's my script:

var series = [
{name: 'Company A', product: 'A1',location:'USA'},
{name: 'Company A', product: 'A2',location:'Mexico'},
{name: 'Company A', product: 'A3',location:'China'},
{name: 'Company B', product: 'B1',location:'USA'},
{name: 'Company B', product: 'B2',location:'Mexico'}
]

$(".company").change(function(){
var company = $(this).val();
var options = '<option value=""><strong>Products</strong></option>';
$(series).each(function(index, value){
if(value.name == company){
options += '<option value="'+value.product+'">'+value.product+'</option>';
}
});

$('.product').html(options);
});


I'd also like to store the name and product in a variable, but that's just for me to show it picked the correct value from the array, it won't be used anywhere else.

Answer Source

I will use helper data attribute in html ! It is also easy to get by using data ! Here I tried with data-location attribute ...

var series = [
{name: 'Company A', product: 'A1',location:'USA'},
{name: 'Company A', product: 'A2',location:'Mexico'},
{name: 'Company A', product: 'A3',location:'China'},
{name: 'Company B', product: 'B1',location:'USA'},
{name: 'Company B', product: 'B2',location:'Mexico'}
]

$(".company").change(function(){
var company = $(this).val();
var options =  '<option value=""><strong>Products</strong></option>';
$(series).each(function(index, value){
    if(value.name == company){
        options += '<option value="'+value.product+'" data-location="'+value.location+'">'+value.product+'</option>';
    }
});

$('.product').html(options).off().on("change",function(){
     console.log($(this).find(":selected").data("location"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="company">
      <option value=''><strong>Name</strong></option>
      <option value="Company A">Company A</option>
      <option value="Company B">Company B</option>
</select>
<select class="product">
      <option value=''><strong>Products</strong></option>
</select>