Home > Blockchain >  Set a value from selector input
Set a value from selector input

Time:04-11

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

CodePudding user response:

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;
}

CodePudding user response:

Still have it be a jQuery object, use .eq(). The .val() method lets you safely set the value.

$("input[name=firstname]").eq(1).val(5)
  • Related