Leonard Febrianto
Leonard Febrianto

Reputation: 984

Can't change font color onClick inside PHP & Javascript

I just want to change font color in href with function. But i seems troubling with quot.

This is my code :

<script>
    <?php foreach($locations AS $loc) { //you could replace this with your while loop query ?>
            var x = '<?php echo $loc['tgl'];?>';
                addMarker(<?php echo $loc["lat"]; ?>, <?php echo $loc["ltd"]; ?> ,'<?php echo $loc["order"]; ?>',x );
                document.getElementById('left').innerHTML += "<?php echo "<li><a href='#' id='".$loc['order']."' onClick='changeColor('".$loc['order']."');return false;'>".$loc["order"]."</a></li>";?>";
            <?php } ?>
</script>

And this is the function :

<script>
    function changeColor(id)
    {
      document.getElementById(id).style.color = "#1FFF48"; // forecolor
    }
</script>

I have tried just only inside in HTML and it succeed. But inside javascript im pretty confused. Any help ?

Upvotes: 1

Views: 95

Answers (3)

Sum IP Cresta
Sum IP Cresta

Reputation: 11

Its the same answer as kim but try using eventlistener inside script tag. This works!!

HTML

<li><a href='#' id='order1'>Order1</a></li>
<li><a href='#' id='order2'>Order2</a></li>

Script

<script>
document.getElementById("order1").addEventListener("click",changeColor);
document.getElementById("order2").addEventListener("click",changeColor);

 function changeColor() {
    this.style.color = "#cecece";
    return false;
 }
</script>

Upvotes: 0

Mani
Mani

Reputation: 2655

Use like this, it will work

<?php $order="onClick=changeColor('".$loc['order']."');return false;";  ?>
    document.getElementById('left').innerHTML += "<?php echo "<li><a href='#' id='".$loc['order']."' $order >".$loc["order"]."</a></li>";?>";

Upvotes: 1

Komal
Komal

Reputation: 2736

After generating your code its look like

<li><a href='#' id='order1' onClick='changeColor("order1");return false;'>Order1</a></li>
<li><a href='#' id='order2' onClick='changeColor("order2");return false;'>Order2</a></li>

check your id also

function changeColor(id)
  {
    alert(id);
    document.getElementById(id).style.color = "#1FFF48"; // forecolor
  }

Upvotes: 0

Related Questions