Forum Moderators: open

Message Too Old, No Replies

Form submit problem

         

gosman

2:09 pm on Oct 27, 2007 (gmt 0)

10+ Year Member



I'm a complete newbie to Javascript. I have a piece of code which validates a postcode and if it's correct submits a form. This works fine. If the postcode is invalid an alert window is displayed. The problem is when ok is clicked on the alert window the form is submitted anyway. Can anybody advise what I need to modify to so the form is not submitted after the ok on the alert window is clicked.

function testPostCode () {
var myPostCode = document.getElementById('postcode').value;
if (checkPostCode (myPostCode)) {
document.getElementById('postcode').value = checkPostCode (myPostCode)
document.pracsearch.submit()
}
else {alert ("Postcode has invalid format")};
}

penders

5:24 pm on Oct 27, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Assuming you are calling your form validation from the onsubmit event of the form, then you just need to return false from your validation routine in order to prevent the form from being submitted, rather than calling submit() directly from your JS. Like so:

HTML:

<form action="..." onsubmit="return testPostCode();"> 
:
<input type="submit" name="btn_submit" value="ok">
</form>

JavaScript:

function testPostCode() { 
var myPostCode = document.getElementById('postcode').value;
if (checkPostCode(myPostCode)) {
document.getElementById('postcode').value = checkPostCode(myPostCode);
return true;
} else {
alert("Postcode has invalid format");
return false;
}
}

(I did just correct the positioning of your semicolons (;) a tad)

If you were to solely rely on JS to submit your form (ie. not actually having a submit button) then it would only get submitted if JS was available, at least this way it is only your client-side validation which is compromised.

gosman

5:57 pm on Oct 27, 2007 (gmt 0)

10+ Year Member



Thanks penders. Worked a treat.