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!

4
  • 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. 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.com/val + api.jquery.com/jQuery.data 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. Commented May 2, 2012 at 12:52
  • 1
    possible duplicate of Set the Value of a Hidden field using JQuery Commented May 2, 2012 at 12:53

3 Answers 3

8

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

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

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

Comments

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;

Comments

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());

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.