Home » Php » Yii2 Button for show Modal Form only work once

Yii2 Button for show Modal Form only work once

Posted by: admin October 26, 2017 Leave a comment

Questions:

I have a button to call Modal Form to create new Approval Letter.
I add that button in form.php.
This is the code:

use yii\widgets\Pjax;
use yii\bootstrap\Modal;

.....
<?php
Modal::begin([
    'header' => '<h4>Create New Approval</h4>',
    'id' => 'modal',
    'size' => 'modal-lg'
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>

<div class="company-form">
<p><?= Html::button('<i class="glyphicon glyphicon-plus"></i> New Approval', ['value' => Url::to('../company/create-modal'), 'class' => 'btn btn-add-al', 'id' => 'modalButton']) ?></p>
.....
</div>

and this is jquery function:

$(function () {
    $('#modalButton').click(function () {
         $('#modal').modal('show')
            .find('#modalContent')
            .load($(this).attr('value'));
    });
});

I have issue, that is the button only work once. So, when I click the button, it will show Modal Form, and if I click outside the Modal Form, the Modal Form automatically closed, and when I try to click again, the button won’didn’t work. It can work again when I refresh the page.

Why it’s happen? and how to fix it?

Answers:

I am using your code in my test bed, and actually it works perfectly.
I have the feeling you might be having a problem regarding where jquery is loading.

By default, jquery loads on the footer of your page, that means that if you are placing your script in the middle of your page it might be responsible of some problems. So please test the following.

  1. Load jquery and other scripts on the header, by adding the following on config\web.php. If it solves the problem you can work later on placing your script inside a js file and load it after jquery.

    'components' => [
    'assetManager' => [
        'bundles' => [
            'yii\web\JqueryAsset' => [
                'jsOptions' => [ 'position' => \yii\web\View::POS_HEAD ],
            ],
        ],
    
  2. Place your script inside a document ready (just in case…)

    $( document ).ready(function() {
        console.log( "ready!" );
        $(function () {
            $('#modalButton').click(function () {
                $('#modal').modal('show')
                    .find('#modalContent')
                    .load($(this).attr('value'));
            });
        });
    });
    
  3. I am using this imports in the view so I guess pjax is not a problem.

    use yii\widgets\Pjax;
    use yii\bootstrap\Modal;
    use yii\helpers\Html;
    use yii\helpers\Url;

  4. Open your console on the browser «I am using chrome» Ctrl+Shift+J (Windows o Linux) o Cmd+Opt+J (Mac). And if it fails post the result, it might be showing you an error or warning.