jQuery $("#radioButton").change(...) not firing during de-selection
Asked Answered
P

9

177

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>
Ptolemaeus answered 3/3, 2011 at 4:52 Comment(4)
your current code will only listen to the change in radio button with id=r1Homework
if id=r2 is selected, id=r1 should be de-selected? de-selection of a radio button isn't captured by this?Ptolemaeus
chk this may be it'll help jsfiddle.net/aqZgsHomework
Don't use removeAttr('disabled'), use prop() to change the state, see my answer.Hamon
L
317

Looks like the change() function is only called when you check a radio button, not when you uncheck it. The solution I used is to bind the change event to every radio button:

$("#r1, #r2, #r3").change(function () {

Or you could give all the radio buttons the same name:

$("input[name=someRadioGroup]:radio").change(function () {

Here's a working jsfiddle example (updated from Chris Porter's comment.)

Per @Ray's comment, you should avoid using names with . in them. Those names work in jQuery 1.7.2 but not in other versions (jsfiddle example.).

Lek answered 3/3, 2011 at 5:8 Comment(6)
The jsFiddle solution is set to Mootools instead of jQuery and prevents it from functioning. Try this solution to see the behavior: jsfiddle.net/N9tBx. I added a log of changes and you can easily see that the change event isn't fired when the checked radio button is unchecked as another is checked.Rayfordrayle
The input "[name=someRadioGroup]" syntax is wrong. The correct syntax is: "input[name=someRadioGroup]:radio". Also worth noting is that this method only works in version 1.7.2 of JQuery. A bug has been submitted for this. See: jsfiddle.net/zn7q2/2 for an example of this bug if you are curious.Jobber
@Ray: The bug only occurs for names with a dot in them. Without the dot it works fine, see jsfiddle.net/zn7q2/4Lek
The example works with dots if you change to "input[name='DateSearchOptions.Test']" (name enclosed between single quotes): jsfiddle.net/4hTxnAmelia
The code "if ($("#myCheckbox").attr("checked"))" Didn't work for me, I had to use "if ($("#myCheckbox").is(":checked"))".Sidestep
This explanation helped me even after 10 Years. This is the beauty of Internet. Thankyou @LekEmploy
H
35
<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

Homework answered 3/3, 2011 at 5:15 Comment(4)
This one works, unlike the other ones that has been marked as correct :SPleat
+1. Andomar's solution worked but this makes more sense to me. Using the class selector prevents having to change the function if the form changes or has a dynamic number of fields. Yay for necro votes! (though now 2 years later jQuery recommends using prop() instead of attr(). api.jquery.com/prop)Cureton
Should change .attr('checked') to .prop('checked').Suppositive
Bad example, this is not how it's done. See my other answer for disabling elements (removing attributes is wrong).Hamon
Y
22

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/

Yolandayolande answered 3/3, 2011 at 5:16 Comment(1)
A variation on this is $("form input:radio").change(...); and test the specific radio button condition prop('checked'). This is very useful when using a dynamic RadioButtonList in ASP.NET.Redding
E
5

This normally works for me:

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

Engenia answered 30/11, 2013 at 17:30 Comment(0)
Z
4

My problem was similar and this worked for me:

$('body').on('change', '.radioClassNameHere', function() { ...
Zilla answered 27/2, 2015 at 13:6 Comment(0)
S
0

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!');
});
Selfridge answered 6/11, 2014 at 15:59 Comment(0)
S
0

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.

Silicify answered 22/4, 2017 at 7:22 Comment(0)
R
0

Same problem here, this worked just fine:

$('input[name="someRadioGroup"]').change(function() {
    $('#r1edit:input').prop('disabled', !$("#r1").is(':checked'));
});
Ratio answered 25/5, 2017 at 19:7 Comment(0)
L
-1

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> ";
Lott answered 10/10, 2016 at 14:34 Comment(1)
This doesn't answer the OPs original question. You're not using jQuery here, and you're using PHP to handle the checking logic, not Javascript.Given

© 2022 - 2024 — McMap. All rights reserved.