简体   繁体   中英

Jquery triggering specific li on click for Bootstrap dropdown

I have two Bootstrap dropdowns that are made dynamically. The second one is made depending on the choice selected in the first one. Both of these dropdowns have an option to add a new choice and push it to the database. The issue I'm having is after pushing to the database, I want to regenerate the dropdowns. Because I use the dynamic code for the dropdown generation elsewhere it can only be called on a "li click event" when a choice is selected. Below is my HTML set up.

<div class="col-md-4">
   <h4>Category</h4>
   <div class="dropdown">
      <button id="category" class="btn btn-default dropdown-toggle short_button text-center" type="button" data- toggle="dropdown" aria-haspopup="true" aria-expanded="true"></button>
      <ul value="" id="subcategory" class="dropdown- menu large_dropdown" aria-labelledby="dropdownMenu1">
         <li value="55"><a href="#" '="">Category1</a></li>
         <li value="17"><a href="#" '="">Category2</a></li>
         <li value="909"><a href="#" data-toggle="modal" data-target="#new_cat_modal">New Category</a></li>
     </ul>
   </div>
</div>

I want to use JQuery to simulate a click so it repopulates the fields. I can successfully do this by simply $("#category li").click(); but the issue is that it selects the next item in the list and generates the wrong list for the next dropdown. I want to know if there is a way to specify which 'li' element I click on so it will generate the list for that one.

Yes you can specify which li should receive the click event by making the selector to jquery more specific. IE

Update to $("#category li[value=55]") Or you could target the li based on it's index within the list through nth-of-type pseudo css $("#category li:nth-of-type(2)") then follow it by the .click() method

With jQuery, you can use the attribute $(this) which refers to the element that is "Pressed on". Then from there you can compare the elements values or go back 1 step to the li and get its current value.

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