-2

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.

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
  • 1
    There are other DOM methods that can get elements like [getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)/[querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) – Patrick Evans Feb 06 '16 at 21:23
  • Could you use jQuery? – kairocks2002 Feb 06 '16 at 21:26
  • 1
    `.getElementsByName("custom_reason")` returns an array you need an index to access one. – Jasen Feb 06 '16 at 21:27

2 Answers2

0

You may use the name instead:

var x = document.getElementsByName("custom_reason")[0];
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
0

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.

dakab
  • 5,379
  • 9
  • 43
  • 67