Frage

I've got a form full of checkboxes, and I'm trying something to update the form options via AJAX (as one option is selected other selections are limited). I had this working via submit buttons, but I'd like to get it done onchange for the select boxes. (Yes I know it's an unusual use of submitting a form).

I tried adding onchange to the input's attribute array, but it doesn't work. Other things like labels, classes etc all get applied fine, but onchange doesn't. Here's one of the checkbox lists:

echo $this->Form->input('Sale.LocationID', array(
        'label' => 'LocationID:',
        'options'=>$locations,
        'multiple' => 'checkbox',
        'onchange'=>"this.form.submit()",
        ));

Is there any way to add an onchange event to my checkboxes in a CakePHP standard manner, or will I have to build the checkboxes without Formhelper to do that?

War es hilfreich?

Lösung

Using inline event-handling is not very efficient, have you considered using jQuery and event delegation?

At the end of your view file;

// Using 'heredoc' here so we don't have to escape quotes
$script = <<< JS

    // this will handle click events on any checkbox on the page
    $(document).on("click", "input[type='checkbox']", function(){
        // or AJAX post here
        this.form.submit();
    });
JS;  // note: must be at the start of the line, no space before JS

// Append the script to the buffer
$this->Js->buffer($script);

And just before the inside your layout (e.g. default.ctp)

// output the JavaScript buffer
echo $this->Js->writeBuffer();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top