Reputation: 973
I have a form with no id
or class
. I need to insert attribute values for input elements.
<form>
<tr><td><input type="text" name="x"/></td></tr>
<tr><td><input type="text" name="y"/></td></tr>
<tr><td><input type="text" name="z"/></td></tr>
</form>
Here's jquery I tried:
var x = $('form').find('input').first().val("some_value");
var y = $('form').find('input').second().val("some_value");
var z = $('form').find('input').third().val("some_value");
// Is there another possible way?
var x = $("form").find('input[name="x"]').val("some_value");
Upvotes: 1
Views: 412
Reputation: 148120
You can use Attribute Equals Selector [name=”value”] to uniquely identify the inputs
$('input[name=x]').val("some_value1");
$('input[name=y]').val("some_value2");
$('input[name=z]').val("some_value3");
Although I wont recommend the method you used to assign values to input, I would suggest you to use find()
once and use the returned object collection to assign values. This will reduce the processing time and increase performance.
var all = $('form').find('input');
all.eq(0).val("some_value1");
all.eq(1).val("some_value2");
all.eq(2).val("some_value3");
Upvotes: 2
Reputation: 781004
If you're giving them all the same value, as it appears in your question, you can simply select them all:
$("form input").val("some_value");
Upvotes: 1
Reputation: 225
// So you can search across the form for all input elements and then iterate to apply the attribute.
var allInputElements = $("form input[type='text']");
$.each(allInputElements,function(index, item){
$(item).attr("disabled","true");
// You can also use item.prop("any property or attribute","value");
});
Upvotes: 1
Reputation: 102
try with this
var x = $('form input[name="x"]').val("some_value_x");
Upvotes: 1
Reputation: 25527
You can use
$("form").find('input[type="text"]]').each(function() {
$(this).attr("your attribute", "your value");
});
Upvotes: 1