PDA

View Full Version : javascript syntax question



Tony
02-03-2011, 10:24 PM
I have a bit of HTML:

<p name="MyText">Foo</p>

How do I change "Foo" to "Bar" as the result of the OnClick on another element?

I'm only a novice at Javascript, and I can't work out how to do it. :badpc:

Tony
03-03-2011, 08:28 AM
OK, I've managed to do it with an image:



function MyFunc ()
{
document.Pic.src="new path to image";
}

<img name="Pic" onclick="MyFunc" src="original image path">



It seems to me I ought to be able to do something like


document.MyText.something="Bar";


but I haven't discovered how to do that.

inphinity
03-03-2011, 09:19 AM
You'll need to give the text element an ID, and then set it's innerHTML value, e.g.:


<script type="text/javascript">
function changeText(){
document.getElementById('changeme').innerHTML = 'New Text';
}
</script>
<p>Here is some <b id='changeme'>Old Text</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>

Tony
03-03-2011, 09:33 AM
Hah! I was about to post that I had found the solution when you just beat me to it. I finally managed to form the correct google query to get the answer I needed. Thanks for the help. That's one of the problems with basically learning javascript via google - knowing what the right question is!