September 25, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


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

comments

1 Response to "Using jQuery to Ensure TextBoxes have Data before Enabling the Submit Button"
  1. Anonymous said...
    October 10, 2011 6:55 AM

    Thanks, mate. It helped a lot!

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions