简体   繁体   中英

Why am I getting this error when I try to open Materialize Modal?

I am trying to display some football fixtures but I am struggling with opening Modals. In each game from each week I want to open one modal where I should display more informations about the respective game. But I get an error in console every time I press any button that should open the modal outside the very first button created. In the Inspect menu I can see that the modals are created and for each modal exist one unique button. But the modals are not displayed on the screen.

Console error

Uncaught TypeError: Cannot read property 'open' of undefined
at HTMLDivElement.<anonymous> (materialize.js:1146)
at Function.each (jquery-2.1.1.min.js:2)
at n.fn.init.each (jquery-2.1.1.min.js:2)
at n.fn.init.jQuery.fn.<computed> [as modal] (materialize.js:1144)
at HTMLAnchorElement.onclick (VM3532 etapa:274)
(anonymous) @ materialize.js:1146
each @ jquery-2.1.1.min.js:2
each @ jquery-2.1.1.min.js:2
jQuery.fn.<computed> @ materialize.js:1144
onclick @ VM3532 etapa:274

PHP code where I echo the modal

$i = 1;
$j = 1;
foreach ($games as $rounds) {
    echo "<div id='et$i' class='tabcontent'>";
    echo "<ul class='collection'>";

    foreach ($rounds as $match) {
        echo "<li class='collection-item'>";
            echo "<div class='row'>";
            echo "<div class='center col s4'>{$match[1]}</div>";
            echo "<div class='center col s1'>-</div>";
            echo "<div class='center col s4'>{$match[0]}</div>";
            echo "<a href='#meci$j' class='secondary-content' onclick=\"$('#modal$j').modal('open');\"> <i class='material-icons'>assessment</i> </a>";
            echo "</div>";

            echo "<div id='modal$j' class='modal'>";
            echo "<div class='modal-content'>";
            echo "<div class='row'>";
            echo "<div class='center col s4'>$match[1]</div>";
            echo "<div class='center col s1'>-</div>";
            echo "<div class='center col s4'>$match[0]</div>";
            echo "</div>";

            echo "</div>";
            echo "</div>";
        echo "</li>";
        $j++;
    }
    echo "</ul>";
    echo "</div>";
    $i++;
}

Using Laravel's default app.css and app.js your code works when you remove the word 'open'

echo "<a href='#meci$j' class='secondary-content' onclick=\"$('#modal$j').modal('open');\">

becomes

echo "<a href='#meci$j' class='secondary-content' onclick=\"$('#modal$j').modal();\">

Edit: In another answer someone mentions that the modals have to be initialized first, for example by using this snippet:

<script>
    $(document).ready(function() {
        $('#modal1').modal();
    });
</script>

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