简体   繁体   中英

passing php variable to javascript onclick function

Not able to pass the php variable into javascript function.

    <p id = "demo"><?php echo $color; ?></p><br>
    <?php while($rows = mysqli_fetch_array($result)) {
         $color = $rows["clr"]; 
    ?>      
    <ul id="menu">
        <li>
            <h onclick="myFunction('<?php echo $color; ?>');">
               <input type ="radio"  name="radio" id ="php" value="<?php echo $color;?>">
               <?php echo $color; ?>
               <!--//<label for = "php" type:<?php echo $rpproduct_typ_color; ?>></label>-->
            </h>
       </li>
    </ul>
    <script type="text/javascript" >
       function myFunction(a) {
          document.getElementById('demo').innerHTML = a;
       }
    </script>
   <?php } ?>

But this way it works fine:-

<ul id="menu">
    <li>
         <input type ="radio" name="radio" id ="php" value="<?php echo $color; ?>" onClick="document.getElementById('demo').innerHTML=this.value">         <?php echo $color; ?>
         <!--//<label for = "php" type:<?php echo $color; ?>  ></label>-->
    </li>
</ul>

But i want to pass multiple values to the onClick function i want the firs tone to work

You have not closed the braces of the line:

<?php while($rows = mysqli_fetch_array($result))
{

The element does not exists, hence I made it a paragraph.

<p id="demo">EMPTY</p>
<br />
<ul id="menu">
    <?php
    $colours = array( '#FF0000', '#00FF00', '#0000FF' );
    foreach( $colours AS $colour ) {
    ?><li>
        <p onClick="changeColour('<?php echo $colour; ?>')">
            <input type ="radio"  name="radio" value="<?php echo $colour; ?>">
            <?php echo $colour; ?> 
        </p>
    </li>
    <?PHP } ?>
</ul>
<script type="text/javascript" >
function changeColour( a ) {
    document.getElementById('demo').innerHTML = a;
}
</script>

Tested and working

Did you mistake h for a headline h1 .. h6 maybe? Since there is no h tag in HTML, at least none that I know of. However, I'd suggest using a block-level element instead, such as div or p .

<li>
  <p onclick="myFunction('<?php echo $color; ?>');">
    <input type ="radio"  name="radio" id ="php" value="<?php echo $color;?>">
    <?php echo $color; ?>
  </p>
</li>

This would give me an output such as this, which works fine in Opera:

<li>
    <p onclick="myFunction('red');" style="background-color: red;">
        <input type ="radio"  name="radio" id ="php" value="red"> red
    </p>
</li>
<li>
    <p onclick="myFunction('blue');" style="background-color: blue;">
        <input type ="radio"  name="radio" id ="php" value="blue"> blue
    </p>
</li>

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