A
A
Andrey2020-01-10 22:21:21
Yii
Andrey, 2020-01-10 22:21:21

YII2 Connecting JS with binding to PHP variable?

Kind.
A very dumb question.
There is YII2, There is a Module that displays N buttons with objects on the form. You need to hang the same JS on each button. Differences in buttons only by ID. In JS, the differences are already in the input parameters from objects and the button code as a trigger. The code is the same.
I only managed to do it like this:
--- php ---

while ( $i <= $categoryCount) {
echo '<button id="btn'.$i.'" >';
echo "<script> $('btn".$i."').on('click', function() { console.log( $('btn".$i."') ); })</script>";
}

The example is very minimalized. If you describe 2-3 teams in this way, then figs with him. An extra 5 minutes will not solve the problem, But if the Code is more or less voluminous, then at first you will get confused in quotes and there ...
In general, I tried to put the JS code into a separate file, but Either the browser or YII no longer wants to accept php variables in js code.
Tell me, how do they generally act in such cases?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-01-10
@skobanev

Good evening.
Give the buttons some css class.
In js, refer to this class and don't mix php with html.

<?php
while ( $i <= $categoryCount) {
?>
<button id="btn<?= $i ?>" >
<?php
}

// регистрируете js код
$this->registerJs("
   $('button.className').on('click', function(){
         console.log($(this).attr('id'))
   })
", yii\web\View::POS_END);
?>

Or put it in a separate file.
PS
Perhaps you are approaching the problem from the wrong side. But for now, do as I wrote.
PS
If js is in a separate file, then putting the php variable there will not work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question