开发者

Code that checks for required text in textboxes upon submit

how can I check if the user filled some textboxes upon submit?开发者_JAVA技巧 My textboxes have different id and name.

If the user did not fill the required like password the form is not continued.

Thank you.


You can do this using JavaScript or within the script itself.

If using javascript, you simply check the form fields against your requirements before allowing the form to submit. However, you may still need to implement this in the script in case ofr some reason they have javascript turned off.

Basically, in the script, you check the values of the form when they submit:

if($_GET['field_name']) !== 'the value I expect') {
  // show the form again with errors
}

// continue

Hope that helps.


Try the below. Naturally you can tweak the form and id's and such, but the basic principle should work. also shown here: http://jsfiddle.net/j3nSB/2/

 <form>
    <input type="text" id="username" value=""/>
    <input type="password" id="password" value="" />
    <input type="submit" id="submitButt" value="Go" />
    </form>

    document.getElementById("submitButt").onclick = function () {
        if(document.getElementById("username").value.length == 0 |document.getElementById("password").value.length == 0) {
          return false;
        }
    }


Assuming you have one form, here is the most simple/generic way I can think of, using plain JavaScript.

<script type="text/javascript">
var arrRequiredFields = [ "txtPassword", "txtEmail" ];
window.onload = function() {
   document.forms[0].onsubmit = function() {
      for (var i = 0; i < arrRequiredFields.length; i++) {
         var field = document.forms[0].elements[arrRequiredFields[i]];
         if (field && field.value.length == 0) {
            alert("Missing required value");
            field.focus();
            return false;
         }
      }
      return true;
   };
};
</script>

Just put the names (not ID) of the required elements, put the code in your page and you're all set.

Live test case: http://jsfiddle.net/kf7pL/


use this:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Its very easy to use, and you can just add a class of 'required' to each required input field.

its as easy as $('#form').validate();

It also supports things like integer and date. Highly recommend it to anyone

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜