获取没有jquery选择器的表单字段

时间:2014-10-18 23:19:40

标签: jquery jquery-selectors

例如:

<form id ="f1">
    <input type="text" id="quantity" />
</form>

显然有一些与jquery选择器相关的开销。所以,一旦我使用选择器获取表单,我不想使用另一个选择器来获取其字段,因为它在下面编码:

var $form = $('#f1');
var $field = $('#f1 #quantity');

是否有替代方法可以在不使用选择器的情况下获取字段数量?是否有类似的东西:

var $qty = $form.quantity;

3 个答案:

答案 0 :(得分:3)

你可以做这样的事情(这里还有一个小提琴来测试:http://jsfiddle.net/zcvv1xwq/3/):

示例HTML:

<form id="test-form">
    <input name="test1" value="1" />
    <input name="test2" value="2" />
    <textarea name="test3">3</textarea>
    <select name="test4">
        <option value=""></option>        
        <option value="4" selected="selected">4</option>
        <option value="Other">Other</option>        
    </select>    
    <input name="test5" type="checkbox" value="5" checked="checked" /> Checkbox 5    
</form>

jQuery示例(基本上与javascript版本相同):

// Get the form element by its ID using jQuery selector.
form = $('#test-form')[0];

// Now we can access the inputs of the form by the `name` HTML attribute.
// For example the first input is named `test1`. Then we can access its value using the `value` attribute
console.log(form.test1.value);

// We can do the same for the second input
console.log(form.test2.value);

// Here is an example using a Textarea.
console.log(form.test3.value);

// Example with select
console.log(form.test4.value);

// Example with checkbox
if (form.test5.checked) {
    console.log(form.test5.value);
}

// Example of looping through elements in form
for (var i = 0; i < form.length; ++i) {
    console.log(form[i]);
}

示例javascript:

// Get the form element by its ID
form = document.getElementById('test-form');

// Now we can access the inputs of the form by the `name` HTML attribute.
// For example the first input is named `test1`. Then we can access its value using the `value` attribute
console.log(form.test1.value);

// We can do the same for the second input
console.log(form.test2.value);

// Here is an example using a Textarea.
console.log(form.test3.value);

// Example with select
console.log(form.test4.value);

// Example with checkbox
if (form.test5.checked) {
    console.log(form.test5.value);
}

// Example of looping through elements in form
for (var i = 0; i < form.length; ++i) {
    console.log(form[i]);
}

答案 1 :(得分:0)

使用.find()

var $field = $form.find('input ')

但是,由于您的输入有一个ID(我们都知道ID必须是唯一的),您可以通过以下方式选择输入:

var $field = $('#quantity');

答案 2 :(得分:0)

您可以使用“find()”在表单中选择所需的元素:

<form>
    <input type="text" id="quantity">
</form>

$(document).ready(function(){
   var $f = $("form");
   var $inp = $f.find("#quantity").val("hi");
});

这是jsfiddle:http://jsfiddle.net/vcpfygpt/2/

选择表单并将其缓存在变量$ f中。方法'find()'用于查找带有#quantity id的输入元素,我们使用val()方法为输入设置一个值。