Balvinder Rayat Balvinder Rayat - 3 months ago 12
HTML Question

Find class inside form validation function

Why I am doing it

I have used jquery validation plugin but it doesn't show desired output when used with bootstrap select. Hence trying to create my own optional method.

What I want to do

I want to search the form called by FormValidation function for specific class name across all inputs, select, checkboxes & radio buttons. If class found then I'll do some validation for quality & values & if validation fails then I would include error class after that element only.

I am here to get some help on searching the form called by FormValidation function for specific class name only

What I have tried

I have tried searching classname using following but it's not searching as desired.

function FormValidation()
{
if($(this).hasClass( "fns" ))
{
//do some validations & show validation output
}
}


I also tried to get form id so that I can search elements of form by form id using
$(this).closest("form").attr("id");
but this is showing undefined.

Please tell me what wrong I am doing here.

<form method="post" class="form-horizontal" id="EMPREG" onSubmit="return FormValidation();" onKeyUp="return FormValidation();">
<input class="form-control fns" type="text" id="Rec_Name" name="Rec_Name" placeholder="Enter Your Name">
<input type="submit" name="Create_Profile" id="Create_Profile" class="btn btn-success btn-md" value="Create Profile"/>
</form>


Js Fiddle for reference https://jsfiddle.net/ttt/cc3r36h0/

Answer

The this keyword in your function refers to widow global object.

If you need to code inline events try to pass the this, and event keywords:

<form method="post" class="form-horizontal" id="EMPREG" onSubmit="return FormValidation(this, event);"
  onKeyUp="return FormValidation(this, event);">
  <input class="form-control fns" type="text" id="Rec_Name" name="Rec_Name" placeholder="Enter Your Name">
  <input type="submit" name="Create_Profile" id="Create_Profile" class="btn btn-success btn-md"value="Create Profile"/>
  </form>

So your function will be:

function FormValidation(obj, evt)
{
        if($(obj).find(".fns").length > 0)
        {
            //do some validations & show validation output
        }
}
Comments