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

0

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

2 Comments

It should be "className" rather than "class", btw.
Oh, didn't notice that ; here's an upvote for your answer, which is then better than mine, on that part :-)
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";

Comments

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.

1 Comment

It should be "className" rather than "class", btw.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.