简体   繁体   中英

Using .change() function to auto-submit form on checkbox change?

This is a bit of a long question so please bear with me guys.

I needed to make a form submit automatically when a checkbox was ticked. So far I have the code below and it works perfectly . The form must submit when the check box is either checked or unchecked. There is some PHP that reads a database entry and shows the appropriate status (checked or unchecked) on load.

<form method="post" id="edituser" class="user-forms" action="--some php here--">
    <input class="lesson" value="l101" name="flesson" type="checkbox" />
</form>
<script>
    $('.lesson').change(function() {
        $('.user-forms').submit(); 
    });
</script>

However, when I introduce a fancy checkbox script which turns checkboxes into sliders it no longer works. The checkbox jQuery script is below:

<script src="'.get_bloginfo('stylesheet_directory').'/jquery/checkboxes.js"></script>
<script type="text/javascript" charset="utf-8">
    $(document).ready(function(){
    $("input[type=checkbox]").tzCheckbox({labels:["Enable","Disable"]});
    });
</script>

The contents of the checkboxes.js called to above is as follows:

(function($){
$.fn.tzCheckbox = function(options){

    // Default On / Off labels:

    options = $.extend({
        labels : ['ON','OFF']
    },options);

    return this.each(function(){
        var originalCheckBox = $(this),
            labels = [];

        // Checking for the data-on / data-off HTML5 data attributes:
        if(originalCheckBox.data('on')){
            labels[0] = originalCheckBox.data('on');
            labels[1] = originalCheckBox.data('off');
        }
        else labels = options.labels;

        // Creating the new checkbox markup:
        var checkBox = $('<span>',{
            className   : 'tzCheckBox '+(this.checked?'checked':''),
            html:   '<span class="tzCBContent">'+labels[this.checked?0:1]+
                    '</span><span class="tzCBPart"></span>'
        });

        // Inserting the new checkbox, and hiding the original:
        checkBox.insertAfter(originalCheckBox.hide());

        checkBox.click(function(){
            checkBox.toggleClass('checked');

            var isChecked = checkBox.hasClass('checked');

            // Synchronizing the original checkbox:
            originalCheckBox.attr('checked',isChecked);
            checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
        });

        // Listening for changes on the original and affecting the new one:
        originalCheckBox.bind('change',function(){
            checkBox.click();
        });
    });
};
})(jQuery);

There is also some CSS that accompanies this script but I am leaving it out as it is not important.

Finally, this is what the jQuery script does to the checkbox:

<input id="on_off_on" class="lesson" value="lesson11-1" name="forexadvanced[]" type="checkbox" style="display: none; ">
<span classname="tzCheckBox checked" class=""><span class="tzCBContent">Disable</span><span class="tzCBPart"></span></span>

When the checkboxes are changed into sliders the .change() function no longer detects the change in the checkboxes status.

How can I make the .change() function work or is their an alternative function I can use?

Listen for change like this:

 $('.lesson').bind("tzCheckboxChange",function() {
      $('.user-forms').submit(); 
 });

Modify the plugin by adding the line:

 $(originalCheckBox).trigger("tzCheckboxChange");

after

 checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);

This way, anytime you use this plugin, you can listen for tzCheckboxChange instead of just change .
I don't really know what's going on with the plugin, but seems kinda funky for it to be listening for a change event when it would only be fired through trigger (unless it doesn't hide the original checkbox).

This plugin changes your checkboxes to span elements and hides the actual checkboxes themselves. Thus, when you click on them, nothing happens. Since span elements don't have onchange events, you can't bind change events to these.

However, span elements do have click events, meaning that you could instead bind a click event to the generated spans, using Firebug or Chrome Debugger to locate the correct element to bind to.

Your click-handler can then take the same action your change event would normally take if the plugin weren't being used.

Here is an example:

HTML (Source):

<!-- This is a checkbox BEFORE running the code that transforms the checkboxes 
   into sliders -->
<li>
    <label for="pelda1">Opció 1:</label>
    <input class="pelda" type="checkbox" id="pelda1" name="pelda1" />
</li>

HTML (Generated From Chrome Debugger):

NOTE: This is the generated HTML after running the JavaScript that converts checkboxes to sliders! You must bind your click event AFTER this code is generated.

<li>
    <label for="pelda1">Option 1:</label>

    <!-- The hidden checkbox -->
    <input class="pelda" type="checkbox" id="pelda1" name="pelda1" style="display: none; " />

    <!-- the "checked" class on the span gets changed when you toggle the slider 
         if it's there, then it's checked. This is what you're users are actually
         changing. 
    -->
    <span class="tzCheckBox checked">
        <span class="tzCBContent">active</span>
        <span class="tzCBPart"></span>
    </span>
</li>

JavaScript:

NOTE: This must be bound AFTER converting the checkboxes to sliders. If you try it before, the HTML won't yet exist in the DOM!

$('.tzCheckBox').click(function() {

    // alert the value of the hidden checkbox
    alert( $('#pelda1').attr("checked") );

    // submit your form here
});

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