Using jQuery to Ensure TextBoxes have Data before Enabling the Submit Button

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:

clip_image002

However if they leave just one field blank, the Submit button will be disabled:

clip_image004






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

2 comments:

Anonymous said...

Thanks, mate. It helped a lot!

Abdus Salam said...

it could not work?!

if (textEntered) {
$("#btnSubmit").attr("disabled", "");
} else {
$("#btnSubmit").attr("disabled", "disabled");
}


is these right?