In my HTML I have:
<div>
<input type="hidden" id="field" value="-1"/>
</div>
In my jQuery I have:
var fieldInput = $("#field");
if(someBoolIsTrue)
fieldInput.value = 4;
After this JS executes, I go to print the value of the hidden field
, and it tells me it's still -1
. Am I using jQuery incorrectly here?!? Thanks in advance!
In my HTML I have:
<div>
<input type="hidden" id="field" value="-1"/>
</div>
In my jQuery I have:
var fieldInput = $("#field");
if(someBoolIsTrue)
fieldInput.value = 4;
After this JS executes, I go to print the value of the hidden field
, and it tells me it's still -1
. Am I using jQuery incorrectly here?!? Thanks in advance!
-
2
The value returned from
$("#field")
is not the raw DOM node; it's a jQuery wrapper. Thus the DOM API (like the "value" property) is not directly available. You can get the DOM node out of it, or you can use jQuery APIs to do what you need. – Pointy Commented May 2, 2012 at 12:49 - 2 It is frustrating when people fail to google for an answer or read the relevant documentation api.jquery./val + api.jquery./jQuery.data – Blowsie Commented May 2, 2012 at 12:50
- @Pointy You should post this as an answer. None of the other answerers cared to provide an explanation. – kapa Commented May 2, 2012 at 12:52
- 1 possible duplicate of Set the Value of a Hidden field using JQuery – Felix Kling Commented May 2, 2012 at 12:53
3 Answers
Reset to default 8You should set the value like fieldInput.val(4);
Another method would be fieldInput[0].value = 4;
For jQuery object you have to use val
method:
var fieldInput = $("#field");
if(someBoolIsTrue)
fieldInput.val(4);
Or without using jQuery:
document.getElementById("field").value = 4;
To set the value in the input with id field
$("#field").val("your value");
To get the value from it ( Ex : alert the value)
alert($("#field").val());