Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 required attribute to fire jquery event

I am making a form in which I am using required attribute on its elements. Now consider the following situation-

The form is divided in two tabs say General Details and 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.

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. So I cannot use per form based JS validation.

like image 834
Chetan Avatar asked Aug 17 '15 10:08

Chetan


1 Answers

See how the required field is selected with the :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.

like image 156
user3154108 Avatar answered Oct 02 '22 14:10

user3154108