0

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!

Brad Fox
  • 685
  • 6
  • 19
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756
  • 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 May 02 '12 at 12:49
  • 2
    It is frustrating when people fail to google for an answer or read the relevant documentation http://api.jquery.com/val/ + http://api.jquery.com/jQuery.data/ – Blowsie May 02 '12 at 12:50
  • @Pointy You should post this as an answer. None of the other answerers cared to provide an explanation. – kapa May 02 '12 at 12:52
  • 1
    possible duplicate of [Set the Value of a Hidden field using JQuery](http://stackoverflow.com/questions/5998385/set-the-value-of-a-hidden-field-using-jquery) – Felix Kling May 02 '12 at 12:53

3 Answers3

8

You should set the value like fieldInput.val(4);

Another method would be fieldInput[0].value = 4;

Sethunath K M
  • 4,702
  • 3
  • 28
  • 42
2

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;
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

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());
Shyju
  • 214,206
  • 104
  • 411
  • 497