Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering event manually in JS Helper CakePHP

I stuck in a situation. I am using JS Helper. I used the following code.

<?php $this->Js->get('#client_id')
        ->event('change', $this->Js->request(array('action' => '../ajax/get_client_location_and_process'),
                   array('update' => '#client_location_process',
                     'async' => false, 
                     'dataExpression' => true,
                     'method' => 'post',
                     'evalScripts' => true,
                     'data' => $this->Js->serializeForm(array('isForm' => True, 'inline' => True))
                     )
                   )
        );

I want to trigger the change event on page load. If I am using document.ready method then it is not working. and I unable to find the JS Helper method where we can explicitly trigger some event on controls. Please suggest the code how can I perform JQuery trigger() like functionality on form elements whenever I need it.

like image 396
Arun Jain Avatar asked Jul 03 '12 06:07

Arun Jain


1 Answers

Since you already found out about .trigger() in jQuery, you can just use it along with your view code:

<?php 
    // Your view code
?>
<script>$('#client_id').trigger('change');</script>

Alternatively, if you still prefer to do it via PHP, you can perhaps make your own helper, eg.:

<?php 
class ArunjsHelper extends AppHelper {
    public $helpers = array('Html');

    function trigger($element, $event, $options = array()) {
        return $this->Html->scriptBlock("$('$element').trigger('$event');");
    }
}

Add ArunjsHelper to $helpers at controller:

<?php
class SomeController extends Controller {
    public $helpers = array('Arunjs');

    // Your controller code
}

You can then call it from view:

<h1>Hello</h1>
<p>Your usual view HTML code</p>

<?php // Trigger the change event ?>
<?php echo $this->Arunjs->trigger('#client_id', 'change'); ?>
like image 99
uzyn Avatar answered Sep 28 '22 08:09

uzyn