Reputation: 1397
I have used javascript to add this when a particular page get loaded.
document.getElementById('commit').addEventListener("click", validateSubmit,
false);
this validateSubmit method have some code which will validate form data and it will do this
function validateSubmit(){
//some code
window.addEventListener('submit', newsubmit, true);
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = newsubmit;
}
function newsubmit(event) {
var target = event ? event.target : this;
event.preventDefault();
return false;
}
so for the first time while submitting form by clicking its coming in this method and it is preventing form values to submit and after fixing al those values when i am again trying to click on submit button then its not working,in console i am getting this error-
"Uncaught TypeError: Cannot call method 'preventDefault' of undefined"
Please help me... Thanks in advance..
Upvotes: 0
Views: 2152
Reputation: 1
Try this:
function validateSubmit(){
window.addEventListener('submit', newsubmit, true);
HTMLFormElement.prototype.submit = newsubmit;
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
}
function newsubmit(event) {
var target = event ? event.target : this;
event.preventDefault();
return false;
}
Upvotes: 0
Reputation: 141
Try changing your function declaration from
function newsubmit(event) {
to
var newsubmit = function(event) {
the function has to be declared as a variable if you want to use it as a parameter of an event listener.
Upvotes: 1
Reputation: 40497
I don't think you need to go through such pains to prevent user from submitting incomplete form. Try this:
<form name="form1" id="form1" onsubmit="return validateForm()" ....>
<input type="text" id="txtName" />
</form>
function validateForm()
{
//CHECK IF FORM FIELDS CONTAIN VALID VALUES?
var formValid=....;//validation logic
return formValid;
}
Now if during validation you find any error you will set formValid
variable to false
otherwise if all input is correct set formValid
to true. When form will get
falseas return value from
validateForm` function it will not submit.
Upvotes: 0