简体   繁体   中英

Inject text into HTML form field with Javascript

Can someone explain why this code doesn't add the string Username to the input field?

It runs in the snippet below but not locally on a basic test.html page. Help?

<script type="text/javascript">
document.getElementById("username").value = "Username";
</script>

<input id="username" name="username" value="">

Thanks for any guidance.

 document.getElementById("username").value = "Username"; 
 <input id="username" name="username" value=""> 

The javaScript runs with a virtual machine and acts as an interpreter. So, you need to keep the sequence. You are using the javascript before defining the input element. So, JavaScript does not recognize the element.

Just put the JavaScript code after the HTML element definition:

<input id="username" name="username" value="">

<script type="text/javascript">
document.getElementById("username").value = "Username";
</script>

尝试在主体末尾插入javascript,或创建一个函数并插入onload

<input id="username" name="username" value="">
document.getElementById("username").value = "Username";

Have you tried to create the script after the input field? If you've created the script inside head tag or before you create the input field it shouldn't work as well, because there's no reference to id "username"

It is problem of your code sequence, in your case when browser executes Javascript code username input field is not found in DOM Element of username id.

So change sequence of your code

<input id="username" name="username" value="">

<script type="text/javascript">
document.getElementById("username").value = "Username";
</script>

you are using input element before defining it...

so first define input element then use it in your script

<input id="username" name="username" value="">
<script type="text/javascript">
 document.getElementById("username").value = "Username";
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM