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?

0

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

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 You must run this code AFTER the HTML has been parsed, so put your script just before the closing BODY tag.
1

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.

3 Comments

You're mixing the BOM and the DOM. It works, but really makes no sense.
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.
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.
1

Try this:

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

<script>
    document.getElementsByClassName("bar")[0].value = "newvalue";
</script>

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.