无法从Bootstrap下拉列表中选择选项

时间:2015-01-28 17:13:23

标签: jquery twitter-bootstrap

我无法使用Bootstrap UI来允许用户从此下拉列表中选择一个选项:

<div class="input-group-btn">
    <button id="label" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
        <span id="areaCode">+1</span>
        <span class="caret"></span>
    </button>
    <select id="areaCodes" class="dropdown-menu" role="menu">
        <option value="1">US: +1</option>
        <option value="44">UK: +44</option>
    </select>
</div>

jQuery的:

$("#1, #44").click(function (e) {
    $("#label").html("+" + $(this).attr("id") + " <span class='caret'></span>");
    var phone = $('input[name="phone"]');
    if ($(this).attr("id") == '1') {
        phone.rules('remove', 'phoneUK');
        phone.rules('add', {
            phoneUS: true
        });
    } else {
        phone.rules('remove', 'phoneUS');
        phone.rules('add', {
            phoneUK: true
        });
    }
});

$('.phone').on('input', function (event) {
    this.value = this.value.replace(/[^0-9]/g, '');
});

它只是自动选择&#34; + 1&#34;并关闭。

链接:jsfiddle

2 个答案:

答案 0 :(得分:1)

您需要使用ul和li。而不是选择列表和选项。

来自bootstrap docs的示例

  <div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a class="isSelected"  role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>

更新了jsfiddle http://jsfiddle.net/rt8892rx/3/

这将使用ul和li,并且它具有添加的代码以获取click事件并更改按钮的文本以选择列表之类的功能。

$("#somelist li").click(function(){

    //sets button text
    $("#label").text($($(this).find("a")).text())

    //removes isSelected class
    $("#somelist li a").removeClass("isSelected");

    //add isSlected Class to clicked element
    $($(this).find('a')).addClass("isSelected")
    alert("working")
})

答案 1 :(得分:0)

$(document).on('click', '#areaCodes', function(event){
  event.stopPropagation();
});