zazvorniki
zazvorniki

Reputation: 3602

Jquery traversing up instead of down

I have a bootstrap dropdown that I am trying to populate I guess you would call header with the value, kind of like you would see on a regular html dropdown. So the user knows what they selected in the menu.

My issue is that if you have more than one drop down on a page the jquery will target them both and not just the one I'm selecting from. Normally I would fix this by adding a $(this).parent(), but the html is a bit more complex and I really rather not do a chain of .parent().parent().parent()

There must be a better way of doing this that I'm missing or just plain forgetting.

my html looks like

<p><label class="control-label" data-bind="html: label"></label></p>
<div class="dropdown" data-bind="cssProperties: properties, css: { hidden : EvalDisplay() == false }">
    <button class="btn btn-default dropdown-toggle col-md-12 dropBtn" type="button" id="dropdownMenu1" data-toggle="dropdown">
        <span class='pull-left'  data-bind="value: value,attr: { 'name' : id}"></span>
        <span class="caret pull-right"></span>
        <p class='clearfix'></p>
    </button>
    <ul class="dropdown-menu side-dropdown" role="menu">
        <!-- ko foreach: options -->
            <li role="presentation"><a role="menuitem" tabindex="-1" data-bind="html: Value"></a></li>
        <!-- /ko -->
    </ul>
    <p class='clearfix'></p>
</div>

and my jQuery looks like this

$(".dropdown-menu li a").click(function(){
    $(".dropBtn.btn:first-child").html('<span class="pull-left">'+$(this).text()+'</span><span class="caret pull-right"></span>');
    $(".dropBtn.btn:first-child").val($(this).text());
});

and a jsfiddle to play with http://jsfiddle.net/0p1Lhzq0/

I have been playing with parentsUtil() as well, but that just doesn't seem right.

Any help would be wonderful!

Upvotes: 0

Views: 51

Answers (1)

Barmar
Barmar

Reputation: 780842

Use this:

$(".dropdown-menu li a").click(function(){
    $(this).closest('.dropdown').find('.btn:first-child').html('<span class="pull-left">'+$(this).text()+'</span><span class="caret pull-right"></span>').val($(this).text());
});

Corrected fiddle

Upvotes: 1

Related Questions