1

When I click the submit button, it causes refresh page! But after I delete the tag, it works well.What,s the problem of this, how can I avoid this problem without deleting the tag, the codes are as follows:

<script language="javascript" type="text/javascript">
 function password() {
 var word = document.getElementById("password");
 var load = document.getElementById("display");
 if(word.type=="password"){
  word.type = "text";
  load.value = "hidden"
 }
 else{
  word.type = "password";
  load.value = "display";
 }
 }
</script>
<form>
<input type="password" name="password" value="password" id="password" />
<input type="submit" name="display" onclick="password()" value="display" id="display"/>
</form>
boyden
  • 113
  • 1
  • 1
  • 9

2 Answers2

4

Change type input from submit to button

<input type="button" name="display" onclick="password()" value="display" id="display"/>

<input type="button" /> buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.

<input type="submit"> buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.

Or

You can stop submit form with javascript

$("form").submit(function(e) {
    e.preventDefault();
});
ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
  • 2
    Op is not tagged jQuery and not shown to be using it. Providing library dependent answers is therefore not appropriate...especially when you don't even qualify it as being such – charlietfl Dec 27 '16 at 04:20
  • For the second option with vanilla JS: `var elem = document.getElementbyId('display'); elem.addEventListener('click', function(e) { e.preventDefault(); password(); });` – Alejandro Iván Jan 03 '17 at 14:50
1

You can also do this:

<form action="demo_form.asp" onsubmit="javascript:return false">

to prevent form submit.

Of course, when you need to submit the form (for example, after you have done validating, sanitizing your form), you have to do this:

document.querySelector('form').submit()
vothaison
  • 1,646
  • 15
  • 15
  • The "javascript:" protocol prefix on your `onsubmit` attribute value is not necessary, all `on_____` attributes expect the content to be JavaScript code – scunliffe Jan 01 '17 at 17:15