0

How can I pass variable to other function in this condition , I'm inserting textarea through javascript with single quotes, but when it gets called myFunction(abc123), it looks like this, the function suppose to be like this when it is called - myFunction('abc123')

so what should i do ?

myNum=123;
focusVar = "abc"+myNum;

$("#myDiv").append('<textarea onFocus="onFocusReportReply('+focusVar+')" onBlur="onBlurReportReply()" id="replyReportText'+data.activityId1+'">')
1
  • focusVar = "'abc"+myNum+"'"; Commented Oct 23, 2012 at 10:41

3 Answers 3

2
$("#myDiv").append('<textarea onFocus="onFocusReportReply(\''+focusVar+'\')" onBlur="onBlurReportReply()" id="replyReportText'+data.activityId1+'">')

Backslashes escape special characters, in this case string delimiters.

Sign up to request clarification or add additional context in comments.

Comments

2

You can either use double quotes or escaped single quotes.

var foo = 'onFocus=myFunc("' + focusVar + '") moar';

or

var foo = 'onFocus=myFunc(\'' + focusVar + '\') moar';

To escape special characters, you need a leading backslash. Examples are

\t (tabulator)
\n (line feed)
\\ (backslash)

7 Comments

He can't use double quotes because those delimit his attribute value.
@Asad: thats why my first example just uses doublequotes for the inner parameters. He doesn't need to quote the whole attribute
Perhaps it isn't imperative to quote your attribute values, but it is good practice.
@Asad: I wouldn't know why it is "not good practice" to use an unquotet attribute value. W3C allows for all types, single-quoted, double-quoted and not-quoted.
Well for one, your HTML is instantly non XHTML, and some validators have trouble parsing just HTML if there are unquoted attributes. Another (more significant) disadvantage is that you can't have spaces in your attribute values.
|
0

Enclose your string inside single quotes, like this:

myNum=123;
focusVar = "'abc"+myNum+"'";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.