I want to write JQuery which will find whether Class="Mandatory" exists on the page and if any element is having this class then only perform certain action.
Thanks
Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");
Just check how many elements you hit, when you search for it with jQuery
if ($(".Mandatory").length > 0) { // Do stuff with $(".Mandatory") $(".Mandatory").each(function() { // "this" points to current item in looping through all elements with // class="Mandatory" $(this).doSomejQueryWithElement(); }); }
EDIT If you wanna do that check for your submit button click, just do that check after the click:
$("input[type='submit']").click(function() { if ($(".Mandatory").length > 0) { // Do some code here } });
If you want to only do the action once, you could use:
if ($('.Mandatory').length > 0) { //do your thing }
Otherwise if you want to do it for each Mandatory
element:
$('.Mandatory').each(function(){ //do your thing });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With