简体   繁体   中英

Trying to echo JS function in PHP

I'm trying to echo a js function in HTML string inside PHP echo.

And I can't figure it out :

$MY_JS_FUNCTION = '<script type="text/javascript">item + getLastField2()</script>';

if($row2->type == 'text') {
    echo "<li id='item-".$row2->rank."' class='list_item'>";
    echo "<textarea rows='2' id='".$row2->single_id."' cols='90' name='field[".$MY_JS_FUNCTION."]' data-kind='text' >".$row2->content."</textarea>";
    echo "</li>";
    echo '<br />';
}

Any ideas to get this work? I think I have so much quotes in it or something like that...

Any help would be very very appreciated, thanks!

I'd reccommend storing the name in the database as well. Then you can use $row2->name to insert the right name

Your variable $MY_JS_FUNCTION contains an HTML <script> tag with some (strange) JavaScript code (missing a semi-colon). Based on your code the echo on line 5 results in this HTML:

<textarea ... name='field[<script type="text/javascript">item + getLastField2()</script>]' ... >...</textarea>

This is definitively not valid HTML. And there is your problem...

It appears your intent is to echo that JS so that when the page loads, the JS actually sets the value of the name field for that textarea. If that's the case, a simpler way might be something like this:

$MY_JS_FUNCTION = '<script type="text/javascript">document.getElementById("myTextArea").name = item + getLastField2()</script>';

if($row2->type == 'text') {
    echo "<li id='item-".$row2->rank."' class='list_item'>";
    echo "<textarea rows='2' id='".$row2->single_id."' cols='90' id='myTextArea' data-kind='text' >".$row2->content."</textarea>";
    echo $MY_JS_FUNCTION;
    echo "</li>";
    echo '<br />';
}

That will produce valid HTML. The JS function will fire once that line is reached and update the "name" value to whatever the result of the function is. Be sure to add the "id" field so that the JS knows which element to target.

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