Fetchez la vache
Fetchez la vache

Reputation: 5230

Bootstrap Dropdown selection is setting selection on *all* dropdowns

There are a number of questions on SO asking how to set the value of a selected dropdown, such as How to Display Selected Item in Bootstrap Button Dropdown Title. This works great, until you add a 2nd (or 3rd...) dropdown to the page. What then happens is that selecting a value on dropdown A will set that value on dropdown B and C as well...

Here's my fiddle

$(".dropdown-menu li a").click(function () {
    var item = $(this).text();        
    $(".btn:first-child").text(item);
    $(".btn:first-child").val(item);    
});

The current selector is selecting all dropdowns.. wheras what's needed is to select the button within the selected dropdowns button group, or traversing via parents, both of which I've failed to work out.

Any help appreciated.

Upvotes: 0

Views: 79

Answers (2)

Med
Med

Reputation: 2063

You need to select the btn in the row where you clicked the link. This is how to select the row according to your html

$(".dropdown-menu li a").click(function () {
    var item = $(this).text();   
    var current_row = $(this).parent().parent().parent().parent().parent();
    var current_btn = $(current_row).find(".btn:first-child");

 console.log($(current_row));     
    $(current_btn).text(item);
    $(current_btn).val(item);

});

Upvotes: 1

ChrisThompson
ChrisThompson

Reputation: 2008

You are searching for all buttons when you have $(".btn:first-child")

you need to be relative to your current element:

 $(".dropdown-menu li a").click(function () {
    var item = $(this).text();        
    $(this).closest(".btn-group").find(".btn:first-child").text(item);
    $(this).closest(".btn-group").find(".btn:first-child").val(item);
});

Upvotes: 1

Related Questions