Matt
Matt

Reputation: 1257

Can't select option from Bootstrap dropdown

I can't get the Bootstrap UI to allow the user to choose an option from this dropdown:

<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, '');
});

It just automatically selects "+1" and closes.

Link: jsfiddle

Upvotes: 1

Views: 7409

Answers (2)

mattfetz
mattfetz

Reputation: 425

Instead of a select list and options you need to use ul and li.

Example from 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>

updated jsfiddle http://jsfiddle.net/rt8892rx/3/

This will use the ul and li and it has the added code to get the click event and change the text of the button for select list like functionality.

$("#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")
})

Upvotes: 1

Linesofcode
Linesofcode

Reputation: 5891

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

Upvotes: 1

Related Questions