【问题标题】:Ignore value radiobuttons - iCheck忽略值单选按钮 - iCheck
【发布时间】:2018-07-18 17:11:39
【问题描述】:

我尝试通过这种方式从单选按钮 (iCheck) 中获取值,但始终只返回来自第一个单选按钮的值,而忽略其余的。理论说代码很好,即使返回很糟糕。

Radio box, get the checked value [iCheck]

我的代码:

<div class="step row">
  <div class="col-md-10">
    <h3>YYYYYY.</h3>
    <ul class="data-list-2">
      <li><input name="p1" id="p1" type="radio" class="required check_radio" value="1"><label>Yes</label></li>
      <li><input name="p1" id="p1" type="radio" class="required check_radio" value="0"><label>No</label></li>
      <li><input name="p1" id="p1" type="radio" class="required check_radio" value="2"><label>Meybe</label></li>
    </ul>
  </div>
</div>
<!-- end step -->

我获取价值的方法:

$(document).ready(function() {
  $('#p1').on('ifChecked', function(event) { //try ifClicked - ifToggled 
    alert($(this).val()); // alert value
  });
});

即使选择了另一个选项,也始终返回值1

请帮忙,我整晚都在尝试不同的方法,但不起作用;(

【问题讨论】:

  • 您使用了多个相同的 ID (p1)。改用类。
  • @Alejandro 您的所有单选按钮都有相同的 id 值“p1”。 ID 应该始终是唯一的。如果您想将“ifChecked”事件处理程序添加到所有单选按钮,请从 $('#p1') 更改为 $('.required.check_radio') 以便使用类并将事件处理程序附加到所有单选按钮,# 代表 id,因为您有多个具有相同的 id,它只是默认为第一个。
  • 你能给我举个例子吗,我是新手,我使用 ID 因为我有许多带有不同问题和 p2、p3、p4 的“step row” div ..... ,这是一项调查
  • @Alejandro 我在下面的答案中提供了相关代码。

标签: javascript jquery html icheck


【解决方案1】:

我不确定您是如何为单选按钮生成 id,但 id 属性应该始终是唯一的,因为您希望对单选按钮进行相同的事件处理,只需使用 class 以便它将事件附加到属于该class 的所有单选按钮,然后您不必为每个id 添加事件:

所以不要这样:

//If you did it this way, you'd have to have one of these blocks for each
//unique id belonging to a radio button
$('#p1').on('ifChecked', function(event){ //try ifClicked - ifToggled 
  alert($(this).val()); // alert value
});

改成这样:

//Use the class instead so that the same event handling can be added to all radio
//buttons in one block of code
$('.required.check_radio').on('ifChecked', function(event){ //try ifClicked - ifToggled 
  alert($(this).val()); // alert value
});

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    相关资源
    最近更新 更多