Forum Moderators: open

Message Too Old, No Replies

Special characters giving me problems

         

formasfunction

11:35 pm on Oct 13, 2007 (gmt 0)

10+ Year Member



I have the following script I'm using to change a bit of text:

function swapText(id, text1, text2){
var elem;
elem = document.getElementById(id);
alert(elem.innerHTML);
elem.innerHTML = (elem.innerHTML == text1)? text2 : text1;
}

It's working fine except when the string contains ">>". I tried calling it the following ways and neither of them work:


<a onclick="swapText('optionslink','Options >>','Hide Options >>');" id="optionslink">Options >></a>
<a onclick="swapText('optionslink','Options &gt;&gt;','Hide Options &gt;&gt;');" id="optionslink">Options &gt;&gt;</a>

Any ideas?

encyclo

1:03 am on Oct 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



When you use a special character in Javascript, you have to use the octal-encoded entity reference, not the usual entity references which are used for HTML.

In this instance, the "

>
" symbol when octal-encoded gives you
[b]\u003E[/b]
- so you should try the following:

<a onclick="swapText('optionslink','Options [b]\u003E\u003E[/b]','Hide Options [b]\u003E\u003E[/b]');" id="optionslink">Options [b]&gt;&gt;[/b]</a>

formasfunction

1:18 am on Oct 14, 2007 (gmt 0)

10+ Year Member



Hmmm, that doesn't seem to be working for me. Nothing happens with your code below, though I do get half of a response with this code:

<a onclick="swapText('optionslink','Options \u003E\u003E','Hide Options \u003E\u003E');" id="optionslink">Options \u003E\u003E</a>

What happens is the octal-encoding doesn't work in the initial html render but when you click the link the first time it does display the correct swap with ">>" however it won't switch back after that. Any other ideas?

daveVk

2:03 am on Oct 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Assuming text1, text2 dont contain html markup

function htmlEsc( iS ) {
var aS = iS;
var re = /"/g;
aS = aS.replace(re, "&quot;");
re = /'/g;
aS = aS.replace(re, "&#39;");
re = /</g;
aS = aS.replace(re, "&lt;");
re = />/g;
aS = aS.replace(re, "&gt;");
return aS;
}

function swapText(id, text1, text2){
var elem;
var t1 = htmlEsc( text1 );
var t2 = htmlEsc( text2 );
elem = document.getElementById(id);
alert(elem.innerHTML);
elem.innerHTML = (elem.innerHTML == t1)? t2 : t1;
}

[edited by: daveVk at 2:03 am (utc) on Oct. 14, 2007]

Achernar

2:46 pm on Oct 14, 2007 (gmt 0)

10+ Year Member Top Contributors Of The Month



Here is a solution that works in IE/Moz/Op :

<html>
<script>
function swapText(id, text1, text2){
var elem;
elem = document.getElementById(id);
elem.innerHTML = ((elem.innerText¦¦elem.textContent) == text1)? text2 : text1;
}
</script>
<body>
<a onclick="swapText('optionslink','Options &gt;&gt;','Hide Options &gt;&gt;');" id="optionslink">Options &gt;&gt;</a>
</body>
</html>