这是在Bootstrap中将单选按钮设置为

这是在Bootstrap中将单选按钮设置为

本文介绍了这是在Bootstrap中将单选按钮设置为“选中"的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要重新使用被标记为重复的TIMEX问题,因为我认为这不是重复的问题,而且我遇到了同样的问题.

I am repurposing TIMEX's question that's been marked as duplicate, because I believe it is not a duplicate and I hit the same issue.

如何设置单选按钮检查"在Bootstrap中?

这是我当前的代码:

<div  class="btn-group col-md-2" data-toggle="buttons">
    <label class="btn btn-gender btn-default active">
        <input type="radio" id="gender" name="gender" value="female"> Girls
    </label>
    <label class="btn btn-gender btn-default">
        <input type="radio" id="gender" name="gender" value="male"> Guys
    </label>
</div>

如何设置男性"以使用JavaScript进行检查?

How can I set "male" to checked using JavaScript?

这是我对问题的再现: https://jsfiddle.net/JonathanN/ba7d24k3/

Here's my reproduction of the problem:https://jsfiddle.net/JonathanN/ba7d24k3/

我在getbootstrap.com文档中找不到解决方案,或者在stackoverflow上都找不到解决方案,所以这是我想出的: https://jsfiddle.net/JonathanN/ba7d24k3/2/

I couldn't find a solution in the getbootstrap.com documentation or readily on stackoverflow, so here's what I came up with:https://jsfiddle.net/JonathanN/ba7d24k3/2/

var toggleRadioButton = function ($parent, name, value) {
  var $allButtons = $parent.find('input[name="' + name + '"]');
  $allButtons.prop('checked', false);
  $allButtons.parents('label.btn').removeClass('active');
  var $targetButton = $parent.find('input[name="' + name + '"][value="' + value + '"]');
  $targetButton.prop('checked', true);
  $targetButton.parents('label.btn').addClass('active');
};

我使用了jQuery,但也可以使用更详细的javascript对其进行编码.希望我已经建立了与javascript问题设置单选按钮的基本方法不重复的方法.

I used jQuery, but it could be coded up in more verbose javascript as well. Hopefully I've established that is not a duplicate of the basic how to set a radio button with javascript question.

我的问题:有没有更简单的方法?

My question: Is there an easier way?

推荐答案

如果您做类似的事情怎么办

What if you do something like

要为您要选择的任何单选选项触发点击事件?引导程序可以处理所有CSS类更改等.

to trigger a click event for whichever radio option you want selected? This way bootstrap can handle all the CSS class changes and such.

这篇关于这是在Bootstrap中将单选按钮设置为“选中"的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 22:42