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
Firstly, there is no value attribute available on an li element, and adding non-standard attributes will mean that your page is invalid.
The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.
Attributes define additional characteristics or properties of the element such as width and height of an image. Attributes are always specified in the start tag (or opening tag) and usually consists of name/value pairs like name="value" . Attribute values should always be enclosed in quotation marks.
1. Which of the following is not a type of attribute for input tag? Explanation: Day is not defined in the pre-defined attribute list of input tag. Week attribute defines week and year when used as attribute in input tag.
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();
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.
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.
If you're gonna use .val()
incorrectly, you'll get strange results.
If you're set on using value=""
in an li
, to access it you must use .attr("value")
see the updated fiddle http://jsfiddle.net/3GTtF/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With