1

I obtained a value in PHP and wanna use it in javascript.

Is there any way to do so ??

Here is the code i am using which is not working

$var = "abc"; 

document.getElementById(<?php echo $act;?>).class="active";

I am using echo $var inside the getElementById method..

Pascal MARTIN
  • 385,748
  • 76
  • 642
  • 654
Prashant Singh
  • 3,695
  • 12
  • 60
  • 106

4 Answers4

7

Your code should look like this:

<script type="text/javascript">
    document.getElementById("<?php echo($var); ?>").className = "active";
</script>

Please note that to change the "class" in JavaScript, you have to access it with the "className" property, not "class".

Jordan
  • 30,837
  • 6
  • 53
  • 65
  • You could probably make it a little easier (and safer) by using json_encode(), e.g. `document.getElementById().className = "active";`. – El Yobo Jul 24 '11 at 06:18
1

This should work, if your PHP code (in the Javascript one) is placed in a .php file -- which are executed by the PHP interpreted, while .js ones are not.


Note that you should place quotes arround the id you pass to getElementById :

document.getElementById('<?php echo $act;?>').class="active";

And, of course, your JS code must be placed between <script> tags :

<script type="text/javavascript">
    document.getElementById('<?php echo $act;?>').class="active";
</script>
Pascal MARTIN
  • 385,748
  • 76
  • 642
  • 654
1

That is the correct usage except for one thing: document.getElementById() expects a string, but when you echo $act you get abc without quotes. So you need to do:

document.getElementById("<?php echo $act;?>").className ="active";
Paul
  • 135,475
  • 25
  • 268
  • 257
1

Yes, that should work. But note that PHP is a pre-processor, so your code would end up as:

document.getElementById(abc).class="active";

instead of:

document.getElementById("abc").class="active";

note the missing quote. anyway, I assume you use the name correctly, in your post you declare $var but echo $act.

LeleDumbo
  • 9,082
  • 4
  • 23
  • 38