简体   繁体   English

所需字段验证的jQuery无法正常工作

[英]jQuery of required field validation not working

I have created this very simple code just for my practice. 我已经为我的练习创建了这个非常简单的代码。 I am trying to test the jQuery for the required fields. 我正在尝试测试jQuery的必填字段。 But it is not working. 但这是行不通的。 Can someone tell me why? 有人可以告诉我为什么吗? Also, it would be really helpful if you can also tell how can I improve it. 另外,如果您还可以告诉我如何进行改进,那将非常有帮助。 I was thinking to make it even better by displaying error message below the field instead of the alert box and also to change the text field colour to red if an error occurred. 我当时想通过在字段而不是警报框下面显示错误消息来使它变得更好,并且如果发生错误,还可以将文本字段的颜色更改为红色。

 $(document).ready(function() { $('.btn').click(function() { if ($('#fn').val() == "" || $('#ln').val() == "") { alert('Please complete the required field(s)'); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body style="background-color : black"> <br /><br /><br /> <div style="text-align:center; color:white;"> <form> <strong> First Name &nbsp &nbsp &nbsp &nbsp <input id = "fn" type = "text" /> <br /><br /> Middle Name &nbsp &nbsp &nbsp &nbsp <input id = "ln" type = "text" /> <br /><br /> Last Name &nbsp &nbsp &nbsp &nbsp <input type = "text" /> <br /><br /> Gender &nbsp &nbsp &nbsp &nbsp <select> <option value = "Male">Male</option> <option value = "Female">Female</option> </select> <br /><br /> Married &nbsp &nbsp &nbsp &nbsp <select> <option value = "No">No</option> <option value = "Yes">Yes</option> </select> <br /><br /> Spouse Name &nbsp &nbsp &nbsp &nbsp <input type = "text" /> <br /><br /> DOB &nbsp &nbsp &nbsp &nbsp <input type = "date" /> <br /><br /> Email &nbsp &nbsp &nbsp &nbsp <input type = "text" /> <br /><br /> Age &nbsp &nbsp &nbsp &nbsp <input type = "text" /> <br /><br /> Mobile &nbsp &nbsp &nbsp &nbsp <input type = "text" /> <br /><br /><br /> <button class="btn"> SUBMIT </button> </strong> </form> </div> 

 $(document).ready(function() { $('.btn').click(function() { debugger; var isValidForm = validateFields(); if (isValidForm) { //code to submit form } }); }); function validateFields() { var isValid = true; $('.validate').each(function(index, object) { if (!$(object).val()) { isValid = false; $(object).siblings('.error-msg').show(); } }); return isValid; } 
 * { color: black } .error-msg { color: red; display: none; } 
 <div style="text-align:center; "> First Name <input id="fn" type="text" class="validate" /> <p class="error-msg">Required</p> <br /><br /> Gender <select class="validate"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <p class="error-msg">Required</p><br /><br /> <button class="btn"> SUBMIT </button> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM