最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to store value in HTML input through jQuery - Stack Overflow

programmeradmin3浏览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!

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!

Share Improve this question edited May 3, 2012 at 17:32 Brad Fox 6816 silver badges19 bronze badges asked May 2, 2012 at 12:47 IAmYourFajaIAmYourFaja 57k186 gold badges489 silver badges778 bronze badges 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. – 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
Add a ment  | 

3 Answers 3

Reset to default 8

You 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());
发布评论

评论列表(0)

  1. 暂无评论