0

I need a way to change the value of an input box by referring to it by form and class name. Given a form that looks like this:

<form name="foo">
<input type="text" class="bar" value="someval" />
</form>

Is there a one-line solution to this? I've tried some things such as:

document.foo.getElementsByClassName('bar')[0].setAttribute("value", "newvalue");

And

document.forms['foo'].getElementsByClassName('bar')[0].setAttribute("value", "newvalue");

To no avail. There must be something obvious I'm missing, but what?

Rafe
  • 7,036
  • 5
  • 24
  • 27

3 Answers3

2

This is precisely what .querySelector() was designed to help with. You can pass any valid CSS selector to it and it will return the first element that matches the query or undefined if no match is found.

And, don't use .getElementsByClassName() or document.forms (ever) as they are both ancient techniques that either introduce major performance issues or non-modern approaches that are inferior to the APIs we have today.

// Find the input element with a class of "bar" that is a direct child of a form with a name attribute of "foo"
document.querySelector("form[name='foo'] > input.bar").value = "blah"
<form name="foo">
  <input type="text" class="bar" value="someval" />
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I get the sense of your code but I'm still getting a null reference for some reason. Are there any "gotchas" to this approach when combined with programming MVC C#? – Rafe Apr 22 '19 at 22:38
  • @Rafe You must run this code AFTER the HTML has been parsed, so put your script just before the closing BODY tag. – Scott Marcus Apr 22 '19 at 22:56
1

Try this:

<form>
    <input type="text" class="bar" value="someval" />
</form>

<script>
    document.getElementsByClassName("bar")[0].value = "newvalue";
</script>
Raphael Alvarenga
  • 868
  • 1
  • 7
  • 13
  • [No, no, no!](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) – Scott Marcus Apr 22 '19 at 22:30
0

You can use something like this

document.forms[0].querySelector(".bar").value

And if you have multiple forms, just loop through document.forms and get values by class name, use querySelector or select by id whatever suits you.

Hope this helps.

  • You're mixing the BOM and the DOM. It works, but really makes no sense. – Scott Marcus Apr 22 '19 at 22:14
  • Can you give me more clarification, like as per my understanding BOM would include access and manipulation of the browser window? I understand this is not the most elegant way the code and you answer makes more sense. – Harish Iyer Apr 22 '19 at 22:30
  • `document.forms[0]` Uses the "Browser Object Model", which is a de facto standard from the earliest days of web scripting. `.querySelector()` is part of the W3C Document Object Model standard that all modern code should utilize. – Scott Marcus Apr 22 '19 at 22:31