简体   繁体   中英

How do I get the value of a selected bootstrap dropdown-item using jquery?

I have the following bootstrap dropdown.

I try to get into the console.log the value of the selected dropdown-item with jquery. I can console.log the text, using the below code but for some reason when I change .text() to .val() , I don't get the value/

 $('.dropdown-item').click(function() { console.log( $(this).text() ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action='/' method='get'> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle btn-sm" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select Date </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#" value="1">March 16 to 19 - CANCELLED</a> <a class="dropdown-item" href="#" value="2">March 21 and 22 - REVISED</a> <a class="dropdown-item" href="#" value="3">March 23 to 26 - REVISED</a> <a class="dropdown-item" href="#" value="4">March 28 and 29</a> <a class="dropdown-item" href="#" value="5">March 30 to April 2 - REVISED</a> </div> </div> </form>

https://jsfiddle.net/vkLr7zhe/ use data attribute as solution . I put in fiddle

$('.dropdown-item').click(function() {
  console.log( $(this).data("id") );
});






<a class="dropdown-item"data-id="1" href="#" value="1">March 16 to 19 - CANCELLED</a>

Looks like I had to use the .attr method like below. Thank you to @KevynKlava for the answer

$('.dropdown-item').click(function() {
  console.log( $(this).attr('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