javascript on select change code example

Example 1: on select price change

<select class="form-control calculate" id="size" name="size">
    <option data-price="5.00" value="Small">Small</option>
    <option data-price="10.00" value="Medium">Medium</option>
    <option data-price="15.00" value="Large">Large</option>
</select>

<span id="item-price">00</span>

<script type="text/javascript" src="jquery-1.11.0.js"></script>
<script type="text/javascript">
var basePrice = 0;

$(".calculate").change(function () {
    newPrice = basePrice;
    $(".calculate option:selected").each(function () {
        newPrice += parseFloat($(this).data('price'));
        console.log(typeof newPrice);
    });
    newPrice = newPrice.toFixed(2);
    $("#item-price").html(newPrice);
});
</script>

Example 2: javascript select change selected

const options = Array.from(select.options);
options.forEach((option, i) => {
  if (option.value === use_id) select.selectedIndex = i;
});

Example 3: js select on change value

document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
});

Example 4: dropdown option selection change event in jquery

$("select [name='element_name']").change(function(){
	// condition goes here
});

Example 5: js html textbox on change

<!-- 
	You can use any of the following:
	onkeydown, onkeyup or onchange
 -->

<input type="text" onkeydown="keydownFunction()" 
onkeyup="keyupFunction()" onchange="changeFunction()">

Example 6: js addeventlistener change select

<input id="test" type="text" value="Sélectionnez-moi !" />
<script>
  var elem = document.getElementById('test');
  elem.addEventListener('select', function() {
    alert('La sélection a changé !');
  }, false);
</script>

Tags:

Html Example