jeudi 22 septembre 2016

Can't set data value on checkbox

I'm dynamically adding checkboxes to a form and then doing some validation on return. I also need the data acted upon to display other fields prior to form submission, so I made a separate data field to store its value. I don't seem to be either writing or reading the data attribute correctly.

the HTML structure is generally:

<div class="parent_container">
  <input type="checkbox" id="checkbox1" data-is_checked="no" value="more options?" data-field_type="checkbox" data-required_check="required">
  <label for="checkbox1">More options?</label>
</div>

These blocks will be added dynamically - so the id will be different for each

The jQuery I'm using is:

jQuery(document).ready( function($){
$('.parent_container').on("click", "input:checkbox", function(){
        var checkbox = $(this);
        checkbox.removeData("is_checked");
        if( checkbox.prop("checked") === true ) {
            checkbox.data("is_checked", "yes");
            console.log('true');
            } else {
            checkbox.data("is_checked", "no");
            console.log('false');
        }
    })
});

The script is running and gives appropriate 'true' and 'false' output for multiple checkboxes on the same page.

I don't see the data-is_checked' value changing when inspecting.

Part of my error checking on submit is:

if ( 'checkbox' === $value['field_type'] && 'required' === $value['required_check']) {
     if ( 'yes' !== $_POST['is_checked']) {
        $et_error_message .= sprintf( '<p class="et_pb_contact_error_text">%1$s</p>',
         esc_html__( 'You must accept our terms.', 'et_builder' ) );
        $et_contact_error = true;
    }
}

Irrespective of whether the checkbox is checked or not, the form still submits. If $et_contact_error is set to 'true' in any of my other checks, the form will not submit - which is the desired behavior.

Am I setting the data wrong, accessing the data wrong for verification, or making some other error?




Aucun commentaire:

Enregistrer un commentaire