Here’s a simple way to prevent the user from submitting a form by disabling the submit button until all of the text boxes contain a value.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ensure Text Boxes Have Data</title>
<script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// Set the focus on the fist text box
$("input[type=text]:first").focus();
controlButton();
$("input[type=text]").keyup(function() {
controlButton();
});
function controlButton() {
var textEntered = true;
$("input[type=text]").each(function() {
if (textEntered && $(this).val().length == 0) {
textEntered = false;
}
});
if (textEntered) {
$("#btnSubmit").attr("disabled", "");
} else {
$("#btnSubmit").attr("disabled", "disabled");
}
}
});
</script>
</head>
<body>
<form>
<input id="Text1" type="text" /><br />
<input id="Text2" type="text" /><br />
<input id="Text3" type="text" /><br />
<input id="btnSubmit" type="submit" value="Submit" />
</form>
</body>
</html>
The user will be allowed to submit the form if they have entered data into each text box:
However if they leave just one field blank, the Submit button will be disabled:
Tweet
2 comments:
Thanks, mate. It helped a lot!
it could not work?!
if (textEntered) {
$("#btnSubmit").attr("disabled", "");
} else {
$("#btnSubmit").attr("disabled", "disabled");
}
is these right?
Post a Comment