简体   繁体   中英

Get selected value of jQuery dropdown plugin

I'm using jQuery dropdown plugin and I want to get selected value , but there is no such option in docs, How can I get selected value via jQuery?

 (function($) { $(function() { $('ul').dropdown({ closeReset: false, nested: true, collision: true, selectParents: true }); }); }(jQuery)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dropdown/2.0.3/jquery.dropdown.js"></script> <link rel="stylesheet" href="http://dane.one/wordpress/wp-content/uploads/dropdown.min_.css?ver=7e2962cd876e2a95be90b37baa97b096" type="text/css" /> <ul> <li>group 1 <ul> <li>assest 1 <ul> <li>bingo!</li> </ul> </li> </ul> </li> <li>group 2 <ul> <li>assest 2 <ul> <li>bingo!</li> </ul> </li> </ul> </li> </ul> 

Also this problem asked before in github but no answer. Look like the plugin not working on this snippet, please see demos here (I'm using Nested demo)

Note that, I'm using ul not select option

Care to use select ? documentation used select not ul . That way, you can get selected value. Can't comment so will post here

Updated answer: here's how to get the selected

var selectedValue = '';
$(document).on('click', '.dropdown-menu li.dropdown-item', function(e) {
    selectedValue = $(this).find('span').text();
});

@CodeSavy answer is in the right direction and logic but got some issue. if the creator did not provide an option to get selected value you should do this on your own, open jquery.dropdown.js search for var classes = { you'll find this selected: 'dropdown-selected', so after select each item it will add this class to selected item. in the previous answer you get all items text() after click but below you can get only selected item text()

$(document).on('click', '.dropdown-item', function() {
  if ($(this).hasClass('dropdown-selected')) {
    var val = $(this).text();
    console.log(val);
  }
})

But with some change on plugin script you can add some attribute or value to get better result.

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