Amanda Kitson
Amanda Kitson

Reputation: 5547

jquery validator with select not working

I have just begun to work with the jquery validate plugin but have not been able to make it work as expected.

I have an example up on Fiddle located at http://jsfiddle.net/GWABv/3/

Can anyone tell me what the heck I am doing wrong? I am merely trying to require that the user select an option in the dropdown list, but even when I don't select a value, it comes back saying that the form is valid.

HTML:

<form id="roadForm" method="get" action="">
    <p>
        <label for="editRoad_ProjectClassification">
            <em class="red">*</em> Project Classification:
        </label>
        <select id="editRoad_ProjectClassification" name="editRoad_ProjectClassification"  title="Please select something!" validate="required:true">
            <option value="">Please select</option>
            <option value="1">1</option>
            <option value="2">2</option>
        </select>
    </p>
</form>
<label class="FUNC_saveRecord">
    <span class="icon iconSave"></span>
    <span class="title">Save</span>
</label>

JavaScript:

$('.FUNC_saveRecord').click(function() {
    saveRecord();
});


function saveRecord() {
    var roadFormValidator = $('#roadForm').validate();
    if (!roadFormValidator.valid()) {
        roadFormValidator.showErrors();
    }
    else {
        alert('form is valid');
    }
}

Upvotes: 4

Views: 2262

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

You have a few problems here:

  1. form is misspelled in the opening tag (<focm>) Looks like this was fixed
  2. You need to add a class='required' attribute to the field. validate=required:true won't do it.
  3. You don't need to call validate every time a click occurs. Just calling it once on document.ready will suffice.
  4. No need to manually call showErrors in this case. The plugin will do this for you automatically.

Here's how I would update your code:

HTML:

<form id="roadForm" method="get" action="">
<p>
    <label for="editRoad_ProjectClassification">
        <em class="red">*</em> Project Classification:
    </label>
    <select id="editRoad_ProjectClassification" name="editRoad_ProjectClassification"  title="Please select something!" class="required">
        <option value="">Please select</option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</p>
</form>
<label class="FUNC_saveRecord">
    <span class="icon iconSave"></span><span class="title">Save</span>
</label>

JavaScript:

$("#roadForm").validate();

$('.FUNC_saveRecord').click(function() {
    saveRecord();
});


function saveRecord() {
    var roadFormValidator = $('#roadForm');
    if (roadFormValidator.valid()) {
        alert('form is valid');
    }
}

Updated example: http://jsfiddle.net/hRjJM/

Upvotes: 4

Related Questions