Sunday 22 October 2017

javascript - Differences between and for onclick script handling

itemprop="text">



I've got a
piece of javascript that validates the entries in a form. It looks like
this:



 function testSubmit()
{
var x = document.forms["myForm"]["input1"];

if
(x.value == "") {
alert('Not allowed!!');
return false;

}
return true;
}

function submitForm()
{
if (testSubmit()) {

document.forms["myForm"].submit();


document.forms["myForm"].reset();
}

}


I'm using a button
with onclick="submitForm()" to call it, however when I use a button tag, it seems to
just go through the whole check and do the form action which is post. If I use a input
tag with type="button", that works like expected. Is there a difference in how this
works between the 2 tags? Here's a codepen showing the problem: href="http://codepen.io/anon/pen/OyVGQQ"
rel="nofollow">http://codepen.io/anon/pen/OyVGQQ



The
button on right works gives you a pop and let's you return to the form. The button on
the left gives you a pop-up, but then tries to post the form
anyway.



Answer




If you need to use the button tag, you can
add "return false" after to keep it from submitting by default. href="http://codepen.io/anon/pen/bVdJOm"
rel="nofollow">http://codepen.io/anon/pen/bVdJOm




            type="submit" onclick="submitForm(); return false;"
/>

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...