1

I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

I have tried something like this but it doesn't work:

<script type="text/javascript"> edit-form.value="the new value"; </script>

How can I do this?

5 Answers 5

8

did you try getting this by document.getElementById()

<script type="text/javascript"> document.getElementById("edit-mail").value="the new value"; </script>

assuming edit-mail is your textbox id

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

Comments

0

Try

document.getElementById("edit-mail").value="he new value"

Comments

0

A lot of the time you don't have the luxury of all the form elements having ids. This is how you can make it work with the field only having a name attribute:

document.getElementById('user-registration-form').elements['edit-form'].value = 'new value';

Comments

0
var textfield = document.getElementByName("x");
textfield.value = "My text";

or directly document.getElementByName("x").value = "My text";

Instead of using getElementByName you can use getElementById if you want to get your element depending of its id instead of its name.

Comments

0
<script type="text/javascript">
document.formname.edit-mail.value="the new value";
</script>

1 Comment

I've tweaked the answer for what I presume was a typo. Hope you don't mind.

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.