Home Ask Login Register

Developers Planet

Your answer is one click away!

NotAGoodCoder February 2016

Select an element without ID in JavaScript

I'm having a little problem with changing the value of a textbot. The problem is that there is no id assigned to the textbox, so getElementById does not work, neither does getElementsByName.

<input type="text" class="textbox" name="custom_reason" size="50" maxlength="120" value="">

How would I change it's value?

Thank you.

Answers


Trix February 2016

You may use the name instead:

var x = document.getElementsByName("custom_reason")[0];


dakab February 2016

One option is using querySelector and to include all the element’s features using attribute selectors:

document.querySelector('input.textbox' +
                       '[type="text"][name="custom_reason"]' +
                       '[size="50"][maxlength="120"]' +
                       '[value=""]').value = 'foo';
<input type="text" class="textbox" name="custom_reason" size="50" maxlength="120" value="">

If the name is unique, you might want to use getElementsByName (Fiddle):

document.getElementsByName('custom_reason')[0].value = 'foo';

Note there’s still more, like iterating all inputs or using jQuery.

Post Status

Asked in February 2016
Viewed 3,062 times
Voted 6
Answered 2 times

Search




Leave an answer


Quote of the day: live life