Leetfail
Leetfail

Reputation: 133

Setting a link name in javascript, with PHP variable

What I am trying to do is load a page, get a PHP variable into JavaScript, and set my element (Link) to said variable. Then, when you click on the link, I would like it to change from open or close to close or open. For some reason, the other solutions I have looked at don't seem to work. What seems to be the issue with the following code? I'm slightly confused as to why this isn't working.

<script type="text/javascript">
var state =  "<?php echo $var; ?>";
document.getElementById('open').text = state;
function toggleText(button_id) 
{
   if (document.getElementById('button_id').text == "Open") 
   {
       document.getElementById('button_id').text = "Close";
   }
   else 
   {
     document.getElementById('button_id').text = "Open";
   }
}
</script>
<a id="open" onclick="toggleText('open')" href="#"></a>

Thanks a lot, this is the last leg of my project, and for some reason whatever I try wont make it work.

Notice: I have also tried instead of .text .innerHTML and it also did not work.

Upvotes: 0

Views: 133

Answers (4)

user3874324
user3874324

Reputation:

<script type="text/javascript">
document.getElementById('buttonid').innerHTML = "<?php echo $var; ?>";
function toggleText(button) 
{
   if (button.innerHTML == "Open") 
   {
       button.innerHTML = "Close";
   }
   else 
   {
     button.innerHTML = "Open";
   }
}
</script>
<a id="buttonid" onclick="toggleText(this)" href="#"></a>

Put script after </body> tag

Upvotes: 1

Sheldon Juncker
Sheldon Juncker

Reputation: 617

Have you checked the console? It's always the place to start.

Part of the problem is that you have button_id in single quotes. I assume that button_id is a variable name, and should not be in quotes. Also, you should be using innerHTML instead of text.

This should work:

<script type=.innerHTML/javascript">
var state =  "<?php echo $var; ?>";
document.getElementById('open').innerHTML = state;
function toggleText(button_id) 
{
   if (document.getElementById(button_id).innerHTML == "Open") 
   {
       document.getElementById(button_id).innerHTML = "Close";
   }
   else 
   {
     document.getElementById(button_id).innerHTML = "Open";
   }
}
</script>
<a id="open" onclick="toggleText('open')" href="#"></a>

Upvotes: 1

Bob Brown
Bob Brown

Reputation: 1502

Try this: <a id="button_id" onclick="toggleText('open')" href="#">open</a> And put the script just before the closing </body> tag.

Upvotes: 0

andrew
andrew

Reputation: 9583

try calling document.getElementById('open').innerText= state; on window.onload

window.onload=function(){
     document.getElementById('open').innerText= state;
}

The problem could be that the dom is not ready (the page is not fully loaded) when you try to set the text property

Upvotes: 0

Related Questions