0

I have a form with many input

$("input[name='firstname']")

Return

Object { 0: input.form-control, 1: input.form-control, 2: input.form-control, 3: input.form-control, length: 4, prevObject: {…} }

I search to set a value to the input, so I tried

$("input[name='firstname']")[0].val=12;
$("input[name='firstname']")[0].text=12;

I don't see the value in the input.

So I tried

$("input[name='firstname']")[0].val("12");

Uncaught TypeError: $(...)[0].val is not a function

robert trudel
  • 5,283
  • 17
  • 72
  • 124
  • Does this answer your question? [find first occurrence of class in div](https://stackoverflow.com/questions/6423804/find-first-occurrence-of-class-in-div) – Heretic Monkey Apr 11 '22 at 02:04
  • See also [Jquery Setting Value of Input Field](https://stackoverflow.com/q/47235335/215552) – Heretic Monkey Apr 11 '22 at 02:06
  • Does this answer your question? [jQuery .eq(index) vs \[index\] if both return an object?](https://stackoverflow.com/questions/47341385/jquery-eqindex-vs-index-if-both-return-an-object) – ruleboy21 Apr 11 '22 at 02:39

1 Answers1

1

The jQuery function $(selector) returns a jQuery object which acts somewhat like a collection of native elements.

When accessing indexed properties like [0], it returns the native HTMLElement.

If you want to just access the first matched element within the object but still have it be a jQuery object, use .eq(). The .val() method lets you safely set the value.

$("input[name=firstname]").eq(0).val(12)

Alternately, don't use jQuery at all

// querySelector returns the first match or null
const firstName = document.querySelector("input[name=firstname]");
if (firstName) {
  firstName.value = 12;
}
Phil
  • 157,677
  • 23
  • 242
  • 245