0

I'm trying to pass this string to a javascript function:

<a href="javascript:InsertPhrase('Let%27s%20groove')">Let's groove</a>

and this is the function:

function InsertPhrase(ThisPhrase) {
 document.getElementById("F1").value = document.getElementById("F1").value + decodeURIComponent(ThisPhrase) + " ";
}

I know the apostrophe is screwing things up but I thought that encoding it would fix it, however the function does not get called. Please can someone tell me why and how to fix it?

Andy Groom
  • 619
  • 1
  • 7
  • 15
  • Why would it get called, you put a JS function into the `href` tag... when do you want this to be called? – tymeJV Jul 09 '15 at 16:01
  • 2
    Ew. Linking to JavaScript is a very bad thing to do. Try `href="#" onclick='InsertPhrase('Let\'s groove')"`, or adding an event listener. – Nebula Jul 09 '15 at 16:02
  • It worked for everything which didn't include apostrophes, I didn't realise I was doing it the wrong way in general! I'll use onclick instead... – Andy Groom Jul 09 '15 at 16:03
  • @AndyGroom the reason it wasn't working for the apostrophe is because it's being evaluated as a _URL_ first which is decoding the url-encoded symbols before the _JavaScript_ interpreter sees it, so you're passing `InsertPhrase('Let's groove')` to the interpreter, in which your string is terminated early – Paul S. Jul 09 '15 at 16:06

1 Answers1

0

Use onclick to call a function instead of href.

<a href="#" onclick="InsertPhrase('Let%27s%20groove')">Let's groove</a>

And for other issue look at here how to escape a single quote in javascript

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48