Javascript jQuery $("#radioButton").change(...) 在取消选择期间不触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5176803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:58:11  来源:igfitidea点击:

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

javascriptjqueryhtmlradio-button

提问by antwarpes

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

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.

情况是这样的:我使用 jQuery 来捕获单选按钮中的更改。选择单选按钮时,我启用一个编辑框。当取消选择单选按钮时,我希望禁用编辑框。

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

使能工作。当我在组中选择不同的单选按钮时,不会触发该change事件。有谁知道如何解决这一问题?

<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>

回答by Andomar

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:

看起来该change()函数仅在您选中单选按钮时调用,而不是在取消选中它时调用。我使用的解决方案是将更改事件绑定到每个单选按钮:

$("#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.)

这是一个有效的jsfiddle 示例(根据 Chris Porter 的评论更新。)

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.).

根据@Ray 的评论,您应该避免.在其中使用名称。这些名称在 jQuery 1.7.2 中有效,但在其他版本中无效jsfiddle 示例。)。

回答by Rafay

<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

jQuery部分

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

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

here is the DEMO

这是演示

回答by jterrace

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/

这里的工作示例:http: //jsfiddle.net/Ey4fa/

回答by user3052657

This normally works for me:

这通常对我有用:

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

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

回答by Alex Sim

My problem was similar and this worked for me:

我的问题很相似,这对我有用:

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

回答by vedant

The changeevent 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)

change未在取消选择时触发的事件是所需的行为。您应该在整个单选组上运行选择器,而不仅仅是单个单选按钮。并且您的无线电组应该具有相同的名称(具有不同的值)

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.

我有与您相同的用例,即在选择特定单选按钮时显示输入框。如果事件在取消选择时也被触发,我每次都会收到 2 个事件。

回答by Scaramouche

Same problem here, this worked just fine:

同样的问题,这工作得很好:

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

回答by Marko Letic

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

假设这些单选按钮位于div具有 id 的a 内,radioButtons并且单选按钮具有相同的名称(例如commonName),然后:

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

回答by Sven

With Ajax, for me worked:

使用 Ajax,对我来说:

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:

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:

和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> ";