简体   繁体   中英

Javascript and forms

This is my html:

<form id="questions">
<p>Answer: <input type="text" name="textbox1" size="30" /> 
<button onclick="answers()">Submit</button></p>
</form>

This is my javascript:

function answers () {
   var x = document.getElementById("questions");
   var y = x.elements["textbox1"].value;
   document.write("Hello " +y);
}   

My issue is when I click the button, it flashes the document.write string for a split second. I'm not sure why it's only happening for a split second.

try putting

type="button"

in your button element

  • Don't use document.write() ; it will replace the page.
    Instead, use the DOM APIs.

  • You need to return false from the handler to prevent the default action of submitting the form.

Even though there is no action on your form, some browsers still reload the page on submission, and my guess is this is what's happening.

If you return false on the onclick event, it will stop the default behaviour. You should add an action to the form too, to comply with standards.

<form id="questions" action="#">
    <p>Answer: <input type="text" name="textbox1" size="30" /> 
    <button onclick="return answers()">Submit</button></p>
</form>

function answers () {
   var x = document.getElementById("questions");
   var y = x.elements["textbox1"].value;
   document.write("Hello " +y);
   return false;
}   

return false to avoid the form to be submited

  function answers () {
  var x = document.getElementById("questions");
   var y = x.elements["textbox1"].value;
  document.write("Hello " +y);
  return false;
 }   

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