5

http://jsfiddle.net/3GTtF/2/

<ul>
    <li class="first" value="45">fortyfive</li>
    <li class="second" value="4text5">45</li>
</ul>

<input value="45">

var whatIsValue = $('.first').val();            //  = 45     typeof = number
var whatIsSecondValue = $('.second').val();     //  = 4      typeof = number
var whatIsInputValue = $('input').val();        //  = '45'   typeof = string

Why does var whatIsSecondValue = 4 instead of '4text5'

Why does var whatIsInputValue = '45' instead of 45

dcodesmith
  • 9,285
  • 4
  • 37
  • 38
CRABOLO
  • 8,322
  • 38
  • 38
  • 66
  • possible duplicate of [How can val() return Number?](http://stackoverflow.com/questions/9227268/how-can-val-return-number) – isherwood Jan 15 '14 at 19:01
  • 2
    It's strange than val() works on LI. – A. Wolff Jan 15 '14 at 19:03
  • I see in jQuery source for valHooks method, returning elem.text PS: after testing seems not to be that! `jQuery.find.attr( $('.first')[0], "value" )` returning correct value as we should expect it :( – A. Wolff Jan 15 '14 at 19:09
  • Wait, for me $('.first').val(); returns fortyfive, not for you?! That's was the purpose of my previous comment. {tested on chrome} – A. Wolff Jan 15 '14 at 19:28

4 Answers4

2

As for the WHY i'm not sure but a li tag shouldn't have a value attribute. You should use data-* attribute instead. It is invalid/improper HTML syntax.

As shown below

<ul>
    <li class="first" data-value="45">fortyfive</li>
    <li class="second" data-value="4text5">45</li>
</ul>


var whatIsValue = $('.first').data('value');
var whatIsSecondValue = $('.second').data('value'); // = 4text5 typeof = string
var whatIsInputValue = $('input').val();

Update

Apparently in HTML5 once can use a value attribute, see comments below. In that case to solve this you could use the .prop() or .attr() methods.

Another Update

Because in HTML5 the value attribute on a li is of type integer/number by default. As to why it trims the string to 4, that's a mystery.

enter image description here

dcodesmith
  • 9,285
  • 4
  • 37
  • 38
  • 1
    @RocketHazmat "The ordinal value of the list item. Permitted only if the li element is a child of an **ol** element." Here it is an UL ;) – A. Wolff Jan 15 '14 at 19:13
  • @RocketHazmat From here http://www.w3schools.com/tags/tag_li.asp "Specifies the value of a list item. The following list items will increment from that number (only for
      lists)" I think that means you can use value for any li, whether inside UL or OL , they just won't increment if you use UL. ?
    – CRABOLO Jan 15 '14 at 19:21
  • @AlienArrays: `
      `'s don't have an "order". That's what "ul" stands for "unordered list". So, `value` doesn't mean anything for a `
        `.
    – Rocket Hazmat Jan 15 '14 at 19:23
  • @AlienArrays W3fool is quite confusing on it, that's correct. Sorry i mean http://www.w3fools.com/ – A. Wolff Jan 15 '14 at 19:24