Search code examples
jqueryselectonchange

Get value of dynamically created dropdowns


I have a button that every time you click it, it creates a new row in a table with a and an and an auto-increment in their IDs.

The actual HTML:

<select class="dynService" id="service_1" name="service[]">
<option value="1" data-price="100">Option 1</option>
<option value="2" data-price="150">Option 2</option>
</select>

<input type="text" id="price_1" name="servprice[]" value="" />

So the next time I will click the button it will create the one more row with the same HTML just the service_1 & price_1 will be service_2 and price_2.

My question is how to create onchange of "service_1" to get the data-price from service_1 and place it to price_1 but not change the price_2 value since the user can have many rows of services added and its not fixed.

Thanks


Solution

  • You can use .on() for attaching event to dynamically added element.

    Maintain data-serial additionally to make your job easier. You can do like following:

    $(document).ready(function () {
       $(document).on('change', '.dynService', function () {
          var _targetId = '#price_' + $(this).data('serial');
          $(_targetId).val($('option:selected', this).data('price'));
       });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select class="dynService" id="service_1" data-serial="1" name="service[]">
      <option value="1" data-price="100">Option 1</option>
      <option value="2" data-price="150">Option 2</option>
    </select>
    
    <input type="text" id="price_1" name="servprice[]" value=""/>
       
    <select class="dynService" id="service_2" data-serial="2" name="service[]">
      <option value="1" data-price="100">Option 1</option>
      <option value="2" data-price="150">Option 2</option>
    </select>
        
    <input type="text" id="price_2" name="servprice[]" value=""/>