How to use radio on change event?
You can use this
which refers to the current input
element.
$('input[type=radio][name=bedStatus]').change(function() { if (this.value == 'allot') { alert("Allot Thai Gayo Bhai"); } else if (this.value == 'transfer') { alert("Transfer Thai Gayo"); }});
Note that you are comparing the value against allot
in both if statements and :radio
selector is deprecated.
In case that you are not using jQuery, you can use the document.querySelectorAll
and HTMLElement.addEventListener
methods:
var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');function changeHandler(event) { if ( this.value === 'allot' ) { console.log('value', 'allot'); } else if ( this.value === 'transfer' ) { console.log('value', 'transfer'); } }Array.prototype.forEach.call(radios, function(radio) { radio.addEventListener('change', changeHandler);});
An adaptation of the above answer...
$('input[type=radio][name=bedStatus]').on('change', function() { switch ($(this).val()) { case 'allot': alert("Allot Thai Gayo Bhai"); break; case 'transfer': alert("Transfer Thai Gayo"); break; }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer
A simpler and cleaner way would be to use a class with @Ohgodwhy's answer
<input ... class="rButton"><input ... class="rButton">
Script
$( ".rButton" ).change(function() { switch($(this).val()) { case 'allot' : alert("Allot Thai Gayo Bhai"); break; case 'transfer' : alert("Transfer Thai Gayo"); break; } });