Suppose you have a html form and you need to prevent the submission of a form based on the input provided in a textbox.
The html input type should be “button” in this case.
<input type="button" value="Submit" onclick="checkInput();">
Below is the Javascript code that gets called on the button click:
function checkInput() {
var form = document.getElementById('form1');
var str = document.getElementById("txtBox").value;
if (str == "") {
var r = confirm("Do you want to add the detail in the input box?");
if (r == true) {
document.getElementById("txtBox").focus();
} else {
form.submit();
}
}
else {
form.submit();
}
}
The above code will submit the form if field is not blank. If the field is blank, focus gets set to the textbox field named “txtBox” when clicking on OK button. Clicking on Cancel will again submit the form.