简体   繁体   English

如何从中检索值<input>使用 jQuery?

[英]How to retrieve a value from <input> using jQuery?

I have to hidden input fields such as:我必须隐藏输入字段,例如:

<input name="foo" value="bar">
<input name="foo1" value="bar1">

I'd like to retrieve both of those values and POST them to the server using jQuery.我想检索这两个值并使用 jQuery 将它们发布到服务器。 How does one use the jQuery selector engine to grab those values?如何使用 jQuery 选择器引擎来获取这些值?

As "foo" and "foo1" are the name of you input fields, you will not be able to use the id selector of jQuery (#), but you'll have to use instead the attribute selector:由于“foo”和“foo1”是您输入字段的名称,您将无法使用 jQuery (#) 的 id 选择器,但您必须使用属性选择器:

var foo = $("[name='foo']").val();
var foo1 = $("[name='foo1']").val();

That's not the best option, performance-wise.就性能而言,这不是最佳选择。 You'd better set the id of your input fields and use the id selector (eg $("#foo")) or at least provide a context to the attribute selector:您最好设置输入字段的 id 并使用 id 选择器(例如 $("#foo"))或至少为属性选择器提供上下文:

var form = $("#myForm"); // or $("form"), or any selector matching an element containing your input fields
var foo = $("[name='foo']", form).val();
var foo1 = $("[name='foo1']", form).val();

You should use id's or classes to speed up getting the value process.您应该使用 id 或 classes 来加快获取价值的过程。

ID version (assuming the input has id='foo') ID 版本(假设输入有 id='foo')

var value1 = $('#foo').val();

Classes version (assuming the input has class='foo')类版本(假设输入有 class='foo')

var value1 = $('.foo').val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM