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

2 comments:

  1. Thanks, mate. It helped a lot!

    ReplyDelete
  2. it could not work?!

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


    is these right?

    ReplyDelete