简体   繁体   中英

Selected item on Bootstrap dropdown list

I have a website with Bootstrap framework. I have two very nasty input fields I'm stuck with, because I can't get them to work properly...

One is this Bootstrap Typeahead input field:

<input type="text" id="typeahead" name='name' placeholder='The name' class="form-control" data-provide="typeahead" autocomplete="off" />

The other is this dropdown list:

<div class="btn-group">
            <button class="btn btn-default dropdown-toggle" id="dates-dropdown-button" type="button" data-toggle="dropdown" href="#">
                <?=$reminder_table_th_date?>
                <span class="caret"></span>
              </button>
              <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="name-dates-dropdown">
              </ul>
</div>

(the <li> list is populated via Ajax call)

With both I want to do: if I select one item either on the ajax dropdown field with the typeahead or with the dropdown list the selected item should be the value what the field is showing. I tried many-many ways, for example:

How to Display Selected Item in Bootstrap Button Dropdown Title

Bootstrap 3 dropdown select

Bootstrap typeahead - How to set the default value manually

but none of them is working and I don't know why. I'm not a JS/jQuery guru at all, but that's just suspicious. Where exactly should I place the jQuery code for this functions and how?

PS: Firefox Firebug isn't showing any JS errors, they just don't do anything, the values aren't set OR the function for them isn't called.

This is the jQuery code for the typeahead Ajax call, the dropdown population (this is working well) and there is also one line where the typeahead value should be set (in the updater), but sadly that's not working:

<script type="text/javascript">

    $(document).ready(function() {
      $('#typeahead').typeahead({
        source: function (query, process) {
          $.ajax({
            url: '/functions/name-autocomplete.php',
            type: 'POST',
            dataType: 'JSON',
            data: 'query=' + query,
            success: function(data) {
              process(data);
            }
          });
        },
        displayText: function(item) {
            return item
        },
        updater: function (item) {
            $('#typeahead').typeahead('val', item);
            $.ajax({
            url: '/functions/name-dates-autocomplete.php',
            type: 'POST',
            dataType: 'JSON',
            data: 'query=' + item,
            success: function(data) {
              $('#name-dates-dropdown').html(data);
            }
          });
        }
      });
    });

</script>

1. Display the selected item on Bootstrap dropdown list

In order to handle selections on a bootstrap dropdown list, you can bind an click event handler to the ul.dropdown-menu element .

This enables you to capture click events from the nested li elements as well, which can in fact be treated as selection events.

Assume this html structure:

<div>
    <input type="text"
        id="typeahead"
        name="date"
        placeholder="date"
        class="form-control"
        data-provide="typeahead"
        autocomplete="off" />
</div>

<div class="btn-group">
    <button class="btn btn-default dropdown-toggle"
    id="dates-dropdown-button" type="button"
    data-toggle="dropdown" href="#">
        <!-- Placeholder for the selected th date -->
        <span class="selection"><?=$reminder_table_th_date?></span>
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="name-dates-dropdown">
        <li>12.11.97</li>
        <li>10.01.07</li>
        <li>2.11.2017</li>
    </ul>
</div>

Then you can handle selection on a bootstrap dropdown list with this event handler:

// handles selections on a bootstrap dropdown list
$('.dropdown-menu').click(function (e) {
    var isLITag = e.target && e.target.tagName == 'LI';
    if (isLITag) {
        var selectedValue = $(e.target).text();
        $('#typeahead').typeahead('val', selectedValue);
        // Specifies the display value of the dropdown element
        $('.dropdown-toggle .selection').text(selectedValue);
        e.preventDefault();
    }
});

2. Typeahead value

I think there is a problem how you assign the datasource to the typeahead only the second parameter accepts a datasources . Furthermore typeahead.js provides a richer data source implementations called Bloodhound , it is worth to consider.

I created a demo that makes use of the bloodhound data source. It also demonstrates how to specifies the value of typeahead and how you can handle typeahead selections.

 $(document).ready(function() { // Constructs the suggestion engine with a set of local dummy dates. var dateSet = { name: 'dates', display: 'date', source: new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('date'), queryTokenizer: Bloodhound.tokenizers.whitespace, local: [{ 'date': '12.11.97', 'id': 0 }, { 'date': '2.11.2017', 'id': 1 }, { 'date': '10.01.07', 'id': 2 }] /** * In order to integrate your ajax call * replace the local attribute with: * * remote: { * url: '/functions/name-autocomplete.php?query=%QUERY', * wildcard: '%QUERY' * } * * Twitter provides a list of examples at: * http://twitter.github.io/typeahead.js/examples/ * */ }) }; // Creates the typeahead and assign the dateSet. $('#typeahead').typeahead({ minLength: 1 }, dateSet); // The selection handler sets the value for the drop down-menu // whenever a suggestion is chosen. $('#typeahead').bind('typeahead:select', function(ev, selection) { $('.dropdown-menu').val(selection.date); $('.dropdown-toggle .selection').text(selection.date); }); // handles selections on a bootstrap dropdown list $('.dropdown-menu').click(function(e) { var isLITag = e.target && e.target.tagName == 'LI'; if (isLITag) { var selectedValue = $(e.target).text(); $('#typeahead').typeahead('val', selectedValue); //Specifies the display value of the dropdown element $('.dropdown-toggle .selection').text(selectedValue); e.preventDefault(); } }); }); 
 .tt-menu { background: white; box-shadow: 0 5px 10px rgba(0,0,0,.2); border-radius: 9px; padding: 10px; } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script> <div> <input type="text" id="typeahead" name='name' placeholder='Serach for ...' class="form-control" data-provide="typeahead" autocomplete="off" /> </div> <div class="btn-group"> <button class="btn btn-default dropdown-toggle" id="dates-dropdown-button" type="button" data-toggle="dropdown" href="#"> <!-- Placeholder for the selected th date --> <span class="selection"><?=$reminder_table_th_date?></span> <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="name-dates-dropdown"> <li>12.11.97</li> <li>10.01.07</li> <li>2.11.2017</li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM