简体   繁体   中英

jQuery validation form if input submit is clicked and checkbox is checked

I have a php page in which a user can publish or save his content. before submitting his data (with global array POST), I want to make some input required only if the corrispective checkbox is checked and the input #publish is clicked (not input #save)

My HTML code

<form id="myForm">
    <input type="checkbox" id="page1" name="selected[]" value="page1" />
    <input type="checkbox" id="page2" name="selected[]" value="page2" />

    <input type="text" id="titlePag1" name="titlePag1" value=""/>
    <input type="text" id="textPag1" name="textPag1" value=""/>

    <input type="text" id="titlePag2" name="titlePag2" value=""/>
    <input type="text" id="textPag2" name="textPag2" value=""/>

    <input type="submit" id="save" name="save" value="Save">
    <input type="submit" id="publish" name="publish" value="publish">
</form>

exemple: if checkbox #page2 is checked and i click #publish, #titlePag2 and #textPage2 are required. Else they aren't required.

I'm using jquery validation form, and a solution for the submit (#publish) could be:

jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#myForm').validate({
rules: {
    titlePag1: {
        required: function(element) {
            return $("#publish").val() != "";
        }
    },

    textPag1: {
        required: function(element) {
            return $("#publish").val() != "";
        }
    }
}
});

How can i set another rule for the checkbox checked?

checkBox: {
    required: function(element) {
        return $("#checkbox").attr("checked");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM