[javascript] jQuery $("#radioButton").change(...) not firing during de-selection

About a month ago Mitt’s question went unanswered. Sadly, I’m running into the same situation now.

http://api.jquery.com/change/#comment-133939395

Here’s the situation: I’m using jQuery to capture the changes in a radio button. When the radio button is selected I enable an edit box. When the radio button is de-selected, I would like the edit box to be disabled.

The enabling works. When I choose a different radio button in the group, the change event is not fired. Does anyone know how to fix this?

<input type="radio" id="r1" name="someRadioGroup"/> 

<script type="text/javascript">
    $("#r1").change(function () {
        if ($("#r1").attr("checked")) {
            $('#r1edit:input').removeAttr('disabled');
        }
        else {
            $('#r1edit:input').attr('disabled', true);
        }
    });
</script>

This question is related to javascript jquery html radio-button

The answer is


You can bind to all of the radio buttons at once by name:

$('input[name=someRadioGroup]:radio').change(...);

Working example here: http://jsfiddle.net/Ey4fa/


My problem was similar and this worked for me:

$('body').on('change', '.radioClassNameHere', function() { ...

This normally works for me:

if ($("#r1").is(":checked")) {}


Same problem here, this worked just fine:

$('input[name="someRadioGroup"]').change(function() {
    $('#r1edit:input').prop('disabled', !$("#r1").is(':checked'));
});

<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>                  

jquery part

$(".rg").change(function () {

if ($("#r1").attr("checked")) {
            $('#r1edit:input').removeAttr('disabled');
        }
        else {
            $('#r1edit:input').attr('disabled', 'disabled');
        }
                    });

here is the DEMO


With Ajax, for me worked:

Html:

<div id='anID'>
 <form name="nameOfForm">
            <p><b>Your headline</b></p>
            <input type='radio' name='nameOfRadio' value='seed' 
             <?php if ($interviewStage == 'seed') {echo" checked ";}?> 
            onchange='funcInterviewStage()'><label>Your label</label><br>
 </form>
</div>

Javascript:

 function funcInterviewStage() {

                var dis = document.nameOfForm.nameOfRadio.value;

                //Auswahltafel anzeigen
                  if (dis == "") {
                      document.getElementById("anID").innerHTML = "";
                      return;
                  } else { 
                      if (window.XMLHttpRequest) {
                          // code for IE7+, Firefox, Chrome, Opera, Safari
                          xmlhttp = new XMLHttpRequest();
                      } else {
                          // code for IE6, IE5
                          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                      }
                      xmlhttp.onreadystatechange = function() {
                          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                              document.getElementById("anID").innerHTML = xmlhttp.responseText;
                          }
                      }
                      xmlhttp.open("GET","/includes/[name].php?id="+dis,true);
                      xmlhttp.send();
                  }
              }  

And php:

//// Get Value
$id = mysqli_real_escape_string($db, $_GET['id']);

//// Insert to database
$insert = mysqli_query($db, "UPDATE [TABLE] SET [column] = '$id' WHERE [...]");

//// Show radio buttons again
$mysqliAbfrage = mysqli_query($db, "SELECT [column] FROM [Table] WHERE [...]");
                  while ($row = mysqli_fetch_object($mysqliAbfrage)) {
                    ...
                  }
                  echo" 
                  <form name='nameOfForm'>
                      <p><b>Your headline</b></p>
                      <input type='radio' name='nameOfRadio' value='seed'"; if ($interviewStage == 'seed') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Yourr Label</label><br>
                      <input type='radio' name='nameOfRadio' value='startup'"; if ($interviewStage == 'startup') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Your label</label><br>

                  </form> ";

The change event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)

Consider the following code:

$('input[name="job[video_need]"]').on('change', function () {
    var value;
    if ($(this).val() == 'none') {
        value = 'hide';
    } else {
        value = 'show';
    }
    $('#video-script-collapse').collapse(value);
});

I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.


Let's say those radio buttons are inside a div that has the id radioButtons and that the radio buttons have the same name (for example commonName) then:

$('#radioButtons').on('change', 'input[name=commonName]:radio', function (e) {
    console.log('You have changed the selected radio button!');
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to radio-button

Angular 4 default radio button checked by default Angular2 - Radio Button Binding Detect if a Form Control option button is selected in VBA How to create radio buttons and checkbox in swift (iOS)? How to check if a radiobutton is checked in a radiogroup in Android? Radio Buttons ng-checked with ng-model Multiple radio button groups in MVC 4 Razor Show div when radio button selected Check a radio button with javascript Bootstrap radio button "checked" flag