PDA

View Full Version : Passing Parameter to a JavaScript function


RnD
03-21-2003, 06:07 PM
Consider the following code:

<html>
<head>
<title>Eg1.htm</title>
<script language="JavaScript">
function displayParameter(param1)
{
alert("Parameter: " + param1);
}
</script>
</head>
<body>
<form name=form1>
<table border=1 align=center>
<th>Enter A Parameter</th>
<tr><td><input type=text name=text1></td></tr>
<tr>
<td align=center>
<input type=button value=Go onClick=displayParameter(document.form1.text1.value)>
&nbsp;
<input type=button value=Default onClick=displayParameter("Steven's Call")>
</td>
</tr>
</table>
</form>
</body>
</html>

I want to display the String when I click Default button but I not able to do so. Instead of ' if I give " or $#.. etc than what I should do to display such type of characters.

piglet
03-21-2003, 06:22 PM
Hi.

You need to escape the quote:

<input type=button value=Go onClick="displayParameter(document.form1.text1.value)">

<input type=button value=Default onClick="displayParameter('Steven\'s Call')">

Roy Sinclair
03-21-2003, 06:29 PM
Quote marks should never be considered optional, just because the most popular browsers have a nasty habit of accepting html that isn't correct doesn't mean you should try to take advantage of that. If those browsers get fixed later your code may stop working long after you thought you had it all under control.

Your problem here is related to the fact that you were trying to call a quoted field within a field that should be quoted but wasn't. Using the following lines fixes your sample page:


<input type="button" value="Go" onClick="displayParameter(document.form1.text1.value)">
<input type="button" value="Default" onClick="displayParameter('Steven\'s Call')">


Note the use of \ to escape the embedded ' character within the text.

piglet
04-10-2003, 02:48 PM
onClick="displayParameter('Steven's Call')"

Are you sure? Looks like dodgy quotes to me.

liorean
04-10-2003, 03:51 PM
That's because these forums have some quirks when it comes to escaping. You have to use \\' in a code block to write \'.

Roy Sinclair
04-10-2003, 03:54 PM
Originally posted by piglet
Are you sure? Looks like dodgy quotes to me.

I see I did forget to escape the embedded ' within Steven's. However I wanted to make sure he understood the problem with the missing quote marks around the whole parameter value. You addressed the escaping the quote but didn't mention the missing outside quotes while I addressed the outside quotes but forgot to escape the embedded one. :o