1

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");
3
  • 3
    There is no second or third methods in jQuery Commented Jul 14, 2015 at 6:41
  • why cant you add a id for the element and access it.. Commented Jul 14, 2015 at 6:41
  • Is there a problem you're having, or do you just want 'other ways' of achieving this? Commented Jul 14, 2015 at 6:43

5 Answers 5

2

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");
Sign up to request clarification or add additional context in comments.

Comments

1

You can use

$("form").find('input[type="text"]]').each(function() {
    $(this).attr("your attribute", "your value");
});

Comments

1

try with this

var x  = $('form input[name="x"]').val("some_value_x");

Comments

1

// 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");
   });

1 Comment

You don't need to use .each() -- .attr() can be used on a collection and it will update them all.
1

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

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.