Norgul
Norgul

Reputation: 4783

jQuery select modal

I have a scheduling app done in Laravel which should enable you to pick a period when you would like to reserve an item. If you click on 9:00, you get dropdown list 9:30 onward in 30 min increments. I am using Bootstraps dropdown.

<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Reserve
        until
        <span class="caret"></span></button>
    <ul class="dropdown-menu">
    </ul>
</div>

Dropdown works fine, but I would like to get the picked value somehow

<script>
    $('#confirm-reservation').on('show.bs.modal', function (e) {
        $(this).find('.dropdown-menu li').remove();
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));

        var startTime = moment($(e.relatedTarget).data('start-time')).utc();
        var endTime = moment($(e.relatedTarget).data('end-time')).utc();

        while (startTime < endTime) {
            $(this).find('.dropdown-menu').append('<li><a href="#">' + startTime.format("HH:mm") + '</a></li>');
            startTime.add(30, 'minutes');
        }
    });
</script>

Upvotes: 0

Views: 2315

Answers (2)

clu3Less
clu3Less

Reputation: 1882

Add an event handler on the dropdown list like below,

$(document).on('click','#confirm-reservation .dropdown-menu a', function(){
    console.log("Selected "+ $(this).text());
});

I have delegated the event to document, since the list items will not be present when the event handler is being initialized.

Hope this helps.

Upvotes: 1

Dmitry Ponkin
Dmitry Ponkin

Reputation: 424

This dropdown menu is not a standard form element, so I presume that selecting an option adds a class or id to the selected li element.

Let's say, it adds a class selected to the selected option, in that case the selector you look for will be this:

$(".dropdown-menu").children(".selected");

To find out what exactly happens when you select an option from the dropdown menu, inspect it and edit the selector above as needed.

Upvotes: 0

Related Questions