Skip to content
Fix Code Error

How to use radio on change event?

March 13, 2021 by Code Error
Posted By: Anonymous

I have two radio button
on change event i want change button How it is possible?
My Code

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer

Script

<script>
    $(document).ready(function () {
        $('input:radio[name=bedStatus]:checked').change(function () {
            if ($("input[name='bedStatus']:checked").val() == 'allot') {
                alert("Allot Thai Gayo Bhai");
            }
            if ($("input[name='bedStatus']:checked").val() == 'transfer') {
                alert("Transfer Thai Gayo");
            }
        });
    });
</script>

Solution

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");
    }
});

http://jsfiddle.net/4gZAT/

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);
});
Answered By: Anonymous

Related Articles

  • sql query to find priority jobs
  • How do i update a javascript variable as its value changes?
  • Active tab issue on page load HTML
  • jQuery Mobile: document ready vs. page events
  • Onclick, the button moves down, why can that due to?
  • How to vertically align an image inside a div
  • Jquery If radio button is checked
  • setTimeout function not working : javascript
  • How do I limit the number of digits from 6 to 4 in JS?…
  • How To Check A Radio Button in Vue.JS 2 WITHOUT using…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

SQL/mysql – Select distinct/UNIQUE but return all columns?

Next Post:

How do I split a string, breaking at a particular character?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error