0
<ul class="myul">
    <li value="2" data-liname="2">2</li>
    <li value="3" data-liname="3">3</li>
    <li value="3+" data-liname="3+">3+</li>
</ul>

With jQuery :

$(".myul li").on("click", function(){
    var myval = $(this).data("liname");
    var myval1 = $(this).val();
});

When I select 3+ I can get the value of myval but with myval1 it shows only 3 and not 3+. myval1 works fine for other values. Only when a nimber has the + sign it chooses to ignore it.

What am I doing wrong?

2 Answers 2

2

With li values attributes, they specify a number value for ordering in an ordered list. Only number parts are taken from the values, thus making your 3+ become a 3. Here's a snippet demonstrating what happens:

<ol class="myul">
    <li value="2" data-liname="2">2nd</li>
    <li data-liname="2">3rd</li>
    <li data-liname="2">4th</li>
    <li data-liname="2">5th</li>
  
    <li value="100+@#$**$&">100th, notice string part is removed</li>
    <li>101th</li>

    <li value="105+">105th, notice + is removed</li>
</ol>

Notice that this is an ol, or ordered list. What the value attribute does is set the number of ordering. In the above snippet you can see that the non-number parts are removed from value, leaving only number parts for ordering.


What this all means is that when you call $(this).val(), it returns the value attribute. But since the value attribute gets rid of all parts after the first non-numeric character because they are not used in ordering ordered lists, it gives you 3, instead of 3+.

Sign up to request clarification or add additional context in comments.

6 Comments

So am i ok to use the data-liname attribute? Is this accepted?
@Somename Sure, this is fine. It accepts a string and is good for passing data. :)
@AndrewL. can an anchor tag have value attribute?I tried to access it using an older version of jQuery but it did not work.
@techie_28 The anchor tag doesn't have a value attribute.
@AndrewL.yes it doesnt but would .val() work if I assign value=something on an anchor tag?
|
0

Try below code. This works.

$(".myul li").on("click", function(){
  var myval = $(this).data("liname");
  var myval1 =$(this).attr('value');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.