BarclayVision
BarclayVision

Reputation: 863

JQuery get the value from <li>

trying to get the value from the <li> in JQuery click event. I'm using an unordered list as a selection table in place of a real dropdown list.

HTML:

<ul id="dropdown">
 <li value="1">user name</li>
 <li value="2">user age</li>
 <li value="3">user height</li>
</ul>

JS:

$('#contactdiv1 #dropdown li').click(function(e) {
      var selection = $(this).text(); //this alerts name
      var selection = $(this).value(); // this fails object undefined
      var selection = $(this).find("value").text(); // this is blank
      alert(selection);
     //populateTableRow($('#customer-title'), data, selection);
});

Upvotes: 0

Views: 261

Answers (2)

Vinod Louis
Vinod Louis

Reputation: 4876

Get attribute using .attr value works on form/input elements its not a valid attribute for li

$('#dropdown li').click(function(e) {
     alert($(this).attr("value"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="dropdown">
 <li value="1">user name</li>
 <li value="2">user age</li>
 <li value="3">user height</li>
</ul>

Upvotes: 1

Pablo Recalde
Pablo Recalde

Reputation: 3571

First of all, you should not be using value attribute on <ul> it is reserved only for <ol>.

You could allways use $("selector").attr("attribute") to get the value of any attribute present in your element.

As told in the comments, you should be using a data-* attribute for everything that is not pure HTML.

Upvotes: 2

Related Questions