简体   繁体   English

html5必需属性来触发jquery事件

[英]html5 required attribute to fire jquery event

I am making a form in which I am using required attribute on its elements. 我正在制作一个表单,其中我在其元素上使用required属性。 Now consider the following situation- 现在考虑以下情况 -

The form is divided in two tabs say General Details and Additional Details . 表单分为两个选项卡,如“ General Details和“ Additional Details So while submitting the form if I leave the required field blank on the visible tab then user can view the message. 因此,如果我在可见选项卡上将所需字段留空,则在提交表单时,用户可以查看该消息。 But suppose user is on first tab and error comes on second tab then User cannot view the error popup and he is clueless about why the form is not submitting. 但是假设用户在第一个选项卡上并且第二个选项卡上出现错误,那么用户无法查看错误弹出窗口,并且他对表单未提交的原因一无所知。

Now I am searching for a way a jQuery event can be fired, whenever the required attribute error comes . 现在, 我正在寻找一种方法,只要出现所需的属性错误,就可以触发jQuery事件

So on this event I can program to show the tab on which the error comes. 因此,在此事件中,我可以编程显示错误发生的选项卡。

Please note I know I can use the JS/jQuery based form validation but the main thing is that, this form is being generated by Grails and the required field is auto-applied depending on the database. 请注意我知道我可以使用基于JS / jQuery的表单验证,但主要的是,这个表单由Grails生成,并且根据数据库自动应用必填字段。 So I cannot use per form based JS validation. 所以我不能使用基于表单的JS验证。

See how the required field is selected with the :invalid pseudo class: 查看如何使用:invalid pseudo class选择必填字段:

 jQuery(document).ready(function(){ jQuery('button').on('click',function(){ jQuery('input:invalid').css('background-color', '#F00'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="required test"> <input type="text" required="required" /> <button>click</button> </form> 

You could simply check for the fields visibility, and if not given traverse up to the parent tab, give the parent tab a class which marks the tab label as containing something invalid. 您可以简单地检查字段可见性,如果没有遍历到父选项卡,则为父选项卡提供一个类,该类将选项卡标签标记为包含无效的内容。

One way is to use submit button and call myValidationFunction() method of JavaScript as action. 一种方法是使用提交按钮并调用JavaScript的myValidationFunction()方法作为操作。 (action="myValidationFunction();").

Other way is to use button and call myValidationFunction() method of JavaScript as on Click event of that button. 其他方法是使用按钮并调用JavaScript的myValidationFunction()方法,如该按钮的Click事件。 After that, inside myValidationFunction(), you can use checkValidity() method to check validity of form at once or particular element and run your custom code to shift on particular tab if there is error to show to the user. 之后,在myValidationFunction()中,您可以使用checkValidity()方法一次检查表单的有效性或特定元素,并运行您的自定义代码以在特定选项卡上移动(如果有错误显示给用户)。 function myValidationFunction() { if ( $('#myInput')[0].checkValidity() ) { // code to move to the particular tab } }

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

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