tags:

views:

87

answers:

4

Hi,

i am having a input field with a class = "required" .Now i want to check in JQuery whether the field which is having the class as "required" contains value or not.If not like alerting..

I tried it with.

$("#ResultSubmit").submit(function(){

      if($("#"+<?=$r['Attribute']['id'];?>).fieldValue()=="")
      { 

                       alert("Fill in  "+"<?=$r['Attribute']['label'];?>");
                       $("#"+<?=$r['Attribute']['id'];?>).focus();
                       return false;
      }

     });

How to check if that contains a class with "required".Please suggest me.....

A: 
if ($('#element input').attr('class') == 'required') {
    alert('required);
}

You could also get all required input fields like so

$('input[class=required]');

Of course, if you have multiple classes, you'll need to use the hasClass() method. This is recommend for future maintenance where you may decide you want 2 classes.

alex
Will this work if the element has multiple classes?
kgiannakakis
I'm not 100% sure, so I modified my answer. I actually forgot about hasClass, and you reminded me. Have an upvote :)
alex
+1  A: 

Have a look at hasClass

kgiannakakis
+1  A: 
if($("input.required").val() == "")
            alert("required")
ToRrEs
clever ...
alex
A: 

I will try to solve your problem directly, rather than answer your question itself :)

$("#ResultSubmit").submit(function(){
  $("input.required").each(function() {
    var field = $(this);
    if ($.trim(field.val()) == '') {
      alert("Fill in " + field.prev('label').text());
      field.focus();
      return false;
  }
});

Register this code once on your page - not once per field. Make sure that all required fields have class required and that all required fields have a <label> element in from of them, containing the text that you wish to use in your error messages.

Voila - no more mixing client side and server side code! The javascript can even be in a seperate file.

Jørn Schou-Rode