【问题标题】:Detect radio button changes based on a button id根据按钮 id 检测单选按钮更改
【发布时间】:2023-04-03 17:30:02
【问题描述】:

在某些情况下,我必须检测单选按钮的更改。问题是应用程序只有它感兴趣的按钮的 ID。例如,给定 HTML 片段:

<label class="required">Type</label><br/>
<span class="vertical">
    <input checked="checked" id="diabetes_type-none" name="diabetes_type" type="radio" value="none" /><label for="diabetes_type-none">No diabetes</label><br />
    <input id="diabetes_type-dm1" name="diabetes_type" type="radio" value="dm1" /><label for="diabetes_type-dm1">DM1</label><br />
    <input id="diabetes_type-dm2" name="diabetes_type" type="radio" value="dm2" /><label for="diabetes_type-dm2">DM2</label><br />
    <input id="diabetes_type-other" name="diabetes_type" type="radio" value="other" /><label for="diabetes_type-other">Other type</label>
    <input class="small free" id="diabetes_type-other_more" name="diabetes_type-other_more" type="text" />
</span>

并且给定 ID“diabetes_type-other”,每次用户选中或取消选中“其他类型”按钮时,应用都必须执行一些代码。 only 必须在用户单击此单选按钮时或当用户单击任何其他按钮取消选中先前的“其他类型”选中按钮时执行。如果用户单击 DM1,然后单击 DM2,则不应执行该功能。这是我的方法:

$("#" + _var).change(function() {
    alert('changed');
});

这里的问题是代码是当用户点击“其他类型”而不是当用户取消选中时触发该功能。

其他方法是获取电台名称,然后执行以下操作:

_radioName = "diabetes_type";  // Obtain programmatically
$("input[name=" + _radioName + "]").change(function() {
    alert('changed');
});

现在的问题是这个功能总是在任何按钮点击时触发,我需要只有当用户选中或取消选中给定的单选按钮时才触发该功能。你可以和this jsfiddle一起玩。

【问题讨论】:

    标签: javascript jquery forms


    【解决方案1】:

    小提琴http://jsfiddle.net/sn7eU/1/
    检查此代码,它应该符合您的意愿:

    var _radioName = "diabetes_type";  // Obtain programmatically
    var _var = "diabetes_type-other";
    
    #(document).ready(function(){
        var lastChecked = false;
        $("input[name=" + _radioName + "]").change(function() {
            if(this.id == _var) lastChecked = true;
            else if(lastChecked){
               /*The radio input isn't "other". Check if the last checked element equals
                 "other" (lastChecked == true). If true, set lastChecked to false*/
                lastChecked = false;
            } else return; /*The input isn't "other", and the last checked element isn't 
                             "other". Return now. */
    
            alert('changed');
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 2012-07-08
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多