【问题标题】:How can I check the radio button relative to a textbox?如何检查相对于文本框的单选按钮?
【发布时间】:2013-02-09 03:00:22
【问题描述】:

我正在尝试检查所选文本框的引用,但是当我更改为其他文本框时,第一个单选按钮保持选中状态!而且我不知道如何根据每个文本框检查单选按钮。

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><input type="text" /> <input name="radio" type="radio" value="val1"/></p>
<p><input type="text" /><input name="radio" type="radio" value="val2"/></p>
<p><input type="text" /><input name="radio" type="radio" value="val3"/></p>
<p><input type="text" /><input name="radio" type="radio" value="val4"/></p>
<script>
$("input").focus(function () {
$('input:radio[name=radio]:nth(0)').attr('checked',true);

});
</script>
</body>
</html>

【问题讨论】:

  • 您是说如果用户在文本框内单击,您也想将相应的单选按钮标记为选中?

标签: jquery textbox focus radio-button checked


【解决方案1】:

您可以将.next() 用于您的特定布局。也就是说,考虑到单选按钮紧跟在输入文本之后。

$("input").focus(function() {
  $(this).next(":radio").prop("checked", true);
});

此外,从 jQuery 1.6 开始,建议在这种情况下使用 .prop()

See it here.

【讨论】:

    【解决方案2】:
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
    <p><input type="text" /> <input name="radio" type="radio" value="val1"/></p>
    <p><input type="text" /><input name="radio" type="radio" value="val2"/></p>
    <p><input type="text" /><input name="radio" type="radio" value="val3"/></p>
    <p><input type="text" /><input name="radio" type="radio" value="val4"/></p>
    <script>
    $(':text').focus(function () {
        $(this).parent().children('input[type=radio]').attr('checked',true);
    });
    </script>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 2016-12-10
      • 2019-05-29
      • 2019-02-07
      • 2012-06-09
      • 2012-03-08
      • 2017-03-19
      相关资源
      最近更新 更多