shibbir ahmed shibbir ahmed - 4 months ago 16
jQuery Question

How to change value when select option is change?

Following is my html code which is generated by php while loop :

<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>2</option>
</select>
<select class="menu_extra_item"/>
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>2</option>
</select>

<tr class="menu_extra_item_change">
<td>$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>$10</td>
</tr>


I want to change the value (price like $32) when select option is change.

For e.g.

I select (first select) option `1`then it will be show `$32`
I select (first select) option `2`then it will be show `$62`

I select (second select) option `1`then it will be show `$10`
I select (second select) option `2`then it will be show `$20`


To get this output I am using following jQuery code but it's not working exactly what I want :(

jQuery code :

$(".menu_extra_item").each(function() {
$(this).change(function() {
var menu_extra_item =$(this).val();
var menu_extra_item_change = parseInt($('.menu_extra_item_change').text().replace(/[^0-9.]/g, ""));
alert(menu_extra_item_change);
var total_ex_price = menu_extra_item * menu_extra_item_change;
$(".menu_extra_item_change").each(function() {
$(".menu_extra_item_change").text("$"+total_ex_price);
});
});
});

Answer

You can do that by using data attributes. Check here

https://jsfiddle.net/v6qmhw77/

<select class="change-me" data-price="32" data-target=".element-1">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>
<select class="change-me" data-price="10" data-target=".element-2">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>

<div class="element-1"></div>
<div class="element-2"></div>


jQuery(document).ready(function(){

   $('.change-me').change(function(){
        var target = $(this).data('target');
        var price = $(this).data('price');

        var cost = parseInt(price) * $(this).val();

        $(target).html("$"+cost);
      });
   });
Comments