Milos911
Milos911

Reputation: 433

Jquery validate and default text

I am trying to find a way to easily add default values to form which is using jquery validate plugin. I searched and didn't find anything useful, and the last similar question is one year old. So, to ask again, is there easy way to add default values to form without messing with jquery validate code. And of course, default values should disappear when user start to type inside the field.

Edit: I see that question is little confusing, so here is better explanation. I want to add default text to form, and i want validation plugin to ignore that default value. I know i can add method that will check if value is default value, but since form is really big, i would prefer some other solution. Like some plugin that places default text above input field, so if form gets submitted with that filed not filled by user, it appears to validate plugin as empty.

Upvotes: 0

Views: 3204

Answers (5)

Caimen
Caimen

Reputation: 2619

 <input type="text" name="user" id="user" value="YOUR DEFUALT VALUE" />

or

 $("#user").attr("value", "YOUR DEFAULT VALUE");

Just use the above code in dom ready and it should be fine I would think.

Upvotes: 1

Jack
Jack

Reputation: 8941

If you are talking about the message that is seen after validation fails then you can do something like this. If you are talking a default value for the textbox itself look at the answer from @Caimen.

$("form").validate({
    rules: {FirstName: "required defaultCheck"},
    messages: {
          FirstName: "First name is required"
)};

Even though you've selected your answer this might help someone. If you want the validator to ignore the default text which is what I think you wanted all along you can do this.

 $.validator.addMethod(
            'defaultCheck', function (value, element) {
                if (element.value == element.defaultValue) {
                    return false;
                }
                return true;
  });

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78550

This is how I would do it:

<input name="firstName" value="First Name" defaultValue="First Name">

and then in the validation:

if(object.value != object.defaultValue)
  // validation

Upvotes: 0

toopay
toopay

Reputation: 1635

If you just use that as attractiveness, you can just use placeholder attribute, <input name="search" type="text" placeholder="Enter some keywords..." />

Upvotes: 1

BumbleB2na
BumbleB2na

Reputation: 10763

Expanding on previous answer:

HTML:

<input type="text" name="user" id="user" value="YOUR DEFUALT VALUE" />

You should not clear default values from form fields.

Upvotes: 0

Related Questions