Juan Gous
Juan Gous

Reputation: 249

Make checkbox cause jQuery validation

I have and bootstrap datetimepicker in my form that is a required field to populate the rest of my page.

I can manage to cause validation when I use a submit button, but I have a checkbox that populates fields with the values from the datetimepicker.

I need the checkbox to cause the validation for the datetimepicker without the submit.

My code looks something like this:

//My datepicker
<div id="dtpDate" class="input-append" >
    <input required data-format="yyyy-MM-dd" type="text" style="width: 75%;" />
    <span class="add-on">
        <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
    </span>
</div>

//Checkbox to cause validation
<div>
    <input type="checkbox" data-bind="checked: setdate, click: setdates"/>
</div>


//My Script
$(document).ready(function () {
    $("form").validate();
});

$(function () {
    $('#dtpDate').datetimepicker({
        pickTime: false
    })
});

How do I make the checkbox cause validation? (Without submit)

Thanx in advance

Upvotes: 1

Views: 587

Answers (3)

iAmClownShoe
iAmClownShoe

Reputation: 616

EDIT: this is working and has been tested in jsfiddle.

<form>
<div>
    <input required type="text" />
</div>
<div>
    <input type="checkbox" class="checkBox" />
</div>
<div>
    <input type="submit" />
</div>
</form>

javascript

//My Script
$(document).ready(function () {

    $('.checkBox').click(function(){
        if($(this).is(':checked')){
            $('form').valid();
        }
    });
});

$(function () {
    $('#dtpDate').datetimepicker({
        pickTime: false
    });
});

Upvotes: 1

Sparky
Sparky

Reputation: 98748

Use .valid() to validate the text field upon click of the checkbox.

jQuery:

$(document).ready(function () {

    $("form").validate({
        // your options & rules
    });

    $('#mycheck').click(function () {
        $('#myfield').valid();
    });

});

HTML:

<form>
    <input required="required" type="text" name="myfield" id="myfield" />
    <input type="checkbox" name="mycheck" id="mycheck" />
    ...
</form>

Working Demo: http://jsfiddle.net/rzjRM/

Upvotes: 1

politus
politus

Reputation: 6086

To validate your datetime field call .valid() after you have called validate()

$(document).ready(function () {
    // initialise validation
    $("form").validate();

    // validated the datetime field on checkbox click
    $('#your_checkbox_id').click(function()
      $('#your_datetime_field').valid();
    });
});

Upvotes: 1

Related Questions