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
  • 395,085
  • 80
  • 655
  • 663
Prashant Singh
  • 3,725
  • 12
  • 62
  • 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
  • 31,971
  • 6
  • 56
  • 67
  • 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
  • 395,085
  • 80
  • 655
  • 663
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
  • 139,544
  • 27
  • 275
  • 264
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,192
  • 4
  • 24
  • 38