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!!

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="" method="POST" onsubmit="return checkForm();">
<input type="text" id="must_be_hello" value="?"/>
<input type="submit" value="Submit?"/>

Notice this:

<form action="" 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.

commented: Good explanation for a beginner. +20
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.