Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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..

share|improve this question
2  
possible duplicate of Is it possible to pass a php variable inside javascript? and many many others – deceze Jul 24 '11 at 5:58

4 Answers

up vote 6 down vote accepted

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".

share|improve this answer
You could probably make it a little easier (and safer) by using json_encode(), e.g. document.getElementById(<?php echo json_encode($var); ?>).className = "active";. – El Yobo Jul 24 '11 at 6:18

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>
share|improve this answer
1  
It should be "className" rather than "class", btw. – Jordan Jul 24 '11 at 6:03
Oh, didn't notice that ; here's an upvote for your answer, which is then better than mine, on that part :-) – Pascal MARTIN Jul 24 '11 at 6:13

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";
share|improve this answer

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.

share|improve this answer
1  
It should be "className" rather than "class", btw. – Jordan Jul 24 '11 at 6:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.