In my Submit button I have a JavaScript coded that will validate certain textfields.. The problem is if the value in the text field fails I must make away to stop the form from submitting..

any suggestions? I'm using JSF with this Javascript.. and to get a picture of my button here's the code for that

<h:commandButton value="Submit" 
onclick="javascript:showItem(10,document.getElementById('statForm:txtTo').value,document.getElementById('statForm:txtFrom').value);" />

Thanks in advance!!

9 Years
Discussion Span
Last Post by MattEvans

Here is some example code. The returns are the important bit:

function checkForm()
  var oTarget = document.getElementById('must_be_hello');
    //Returning true! the form will submit.
    return true;
    alert("Sorry you cannot submit anything but hello");
    //Returning false. Not today thanks.
    return false;
<form action="http://google.com" method="POST" onsubmit="return checkForm();">
<input type="text" id="must_be_hello" value="?"/>
<input type="submit" value="Submit?"/>

Notice this:

<form action="http://google.com" method="POST" [B]onsubmit="return checkForm();"[/B]>

Returning this function to the form onsubmit event will make the submit dependant on the return of the function. So, if the function returns false; the onsubmit is cancelled; if the function returns true; the onsubmit continues.

The checkForm function is a silly example; but remember the function(s) that you do use should return a 'true' if submission should continue; and a 'false' if it should be aborted; and importantly; remember that onsubmit is a form event, not a submit button event.

Votes + Comments
Good explanation for a beginner.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.