javascriptjqueryhtmlselectedtext

jquery loop through select tags on option change


I need help looping through all my select tags in my html page and running some functions on each change

<div id="product_options">
     <label>Color</label>
     <select name="productOptions" id="colorOpt" style="margin-bottom:10px;">
          <option value="1">White</option>
          <option value="3">Blue</option>
     </select>
     <label>Size</label>
     <select name="productOptions" id="sizeOpt" style="margin-bottom:10px;">
         <option value="2">9oz</option>
         <option value="4">10oz</option>**strong text**
     </select>
</div>

Everything inside of the main div is variable including the label, names and id's

what i want to do is everything someone updates either one of the selected options i need to figure out which select element they chose and get the value along. So for example if they update the color option to blue i need to trigger a call in jquery to show that select element with id colorOpt was updated with the value of 3

Any ideas I am completely lost as to how to do this. Started with this but not sure if its correct or not

$('#product_options').select("select").each(function(selected, index) {


});

Solution

  • It looks like you started thinking that you'd need to loop through every select...but since you said that you need to "figure out which select element they chose" you can rely on the this keyword inside of a change callback.

    Fiddle: http://jsfiddle.net/vpqh3kjz/

    Code:

    // Every time someone updates either selected option fire a callback
    $('#product_options select').change(function () {
        // `this` represents the element that changed
        var id = this.id;
        var value = this.value;
    
        // Do something with your data here
        console.log('select element id ' + id + ' was updated with ' + value);
    });