【问题标题】:jQueryUI Radio/Check buttons not changing programmaticallyjQueryUI 单选/检查按钮未以编程方式更改
【发布时间】:2011-04-03 22:39:17
【问题描述】:

我可以预测地读取 jQueryUI 单选按钮的值,但是,我无法以编程方式设置它。不管我用什么方法改变单选按钮的值,jQueryUI界面都不会更新它的界面。

<div id="radio">
    <input type="radio" name="radio" value="true" checked="checked" />Yes
    <input type="radio" name="radio" value="false" />No
</div>

<script type="text/javascript">
    $('#radio').buttonset();

    // One of the many ways that won't work.
    $('[name="radio"]:radio:checked').val("false");
</script>

【问题讨论】:

  • 你在哪里使用 jQuery UI?

标签: jquery html jquery-ui


【解决方案1】:

我通常做一个:

$('[name="radio"][value="false"]').prop("checked", true).trigger("change");

请使用“prop”而不是“attr”来改变“checked”状态。

【讨论】:

    【解决方案2】:

    我通常会做一个:

    $('[name="radio"][value="false"]').attr("checked", true).trigger("change");
    

    buttonset("refresh") 调用绑定到 change 事件,当您以编程方式更改值时根本不会触发该事件 - 手动触发它可以解决 ui 问题,您无需担心 buttonset 的位置是

    【讨论】:

      【解决方案3】:

      更新值后,如下所示:

      $('[name="radio"][value="false"]').attr("checked", true);
      

      你需要告诉 jQuery UI 更新,像这样:

      $('#radio').buttonset("refresh");
      

      You can give it a try here.

      【讨论】:

      • 当我回答时,问题的按钮设置部分不存在。 ://
      • 我从来没有想过这个。谢谢。
      • @Yanick - 是......他从一开始就提到了 jQuery UI,这就是为什么我的评论甚至在你的回答询问之前就发布了:)
      • @Nick Crave,我不敢苟同。当我回答这个问题时,只有 HTML 部分作为代码(加上 .val() 调用,就是这样)。没有提到底部套装。虽然我可能已经预料到了,但我认为 OP 并没有使用 JQuery UI。
      • 原始问题标题中包含 jQuery UI,您可以通过单击此处问题的编辑链接来查看修订:stackoverflow.com/posts/3569794/revisions(为什么您认为我在 2 分钟后询问它原来的答案?):)
      【解决方案4】:
      $('[name="state"]:radio:checked').attr('checked', true);   // checked
      $('[name="state"]:radio:checked').removeAttr('checked');   // unchecked
      

      ** 注意 **

      $(':radio').val();  // same as $(':radio').attr('value');
      

      因此:

      $(':radio[checked]').val(); // -> the value of the first checked radio button found
      

      【讨论】:

      • 非常抱歉。考虑到常规单选按钮非常简单,我只是认为这些细节不会太多。 oO./
      猜你喜欢
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多