Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Event Handlers Args as embedded String Vars?

Status
Not open for further replies.

Delvis

Programmer
Dec 21, 2003
10
US
Hello -

How does one add a string variable argument to an event handler that is defined inside a string (typically used for setting innerHTML). Here's an example of what I'm trying to do: ( put idStr as a string arg to the onclick handler )

/****************************************/
function addCommentBox( idStr ) {
var el = document.createElement( "div" );
var input = &quot;<INPUT TYPE='BUTTON' onclick='clk( this, &quot;idStr&quot; )' value='Ok'/>&quot;;
el.innerHTML = input;
document.body.appendChild( el );
}

Is there some solution that involves escaping quotes? Or maybe doing an eval?

Here's a WORKAROUND I developed - create an artificial attribute (tid) to which you set the idStr val, then access via this.tid in the event handler code. But it would be great to find a way to avoid this workaround!

WORKAROUND :
/****************************************/
function addCommentBox( idStr ) {
var el = document.createElement( &quot;div&quot; );
var input = &quot;<INPUT TYPE='BUTTON' idStringVar='&quot; +idStr +&quot;'&quot; +&quot;onclick='clk( this )' value='Ok'/>&quot;;
el.innerHTML = input;
document.body.appendChild( el );
}

/****************************************/
function clk( obj ) {
alert(&quot;got2 testClick, +&quot;id string var : &quot; +obj.idStringVar);
event.cancelBubble = true;
}

Thx for your thoughts or suggestions! - Delvis :)
 

try this - comment out the quotes

var input = &quot;<INPUT TYPE='BUTTON' onclick='clk( this, \&quot;idStr\&quot; )' value='Ok'/>&quot;;

hope this helps

simon
 
Hi Simon -

Thx for your helpful thoughts! Here's how I solved my problem:

/****************************************/
function addCommentBox( idStr ) {
/* ~~~~~~~~~~~~~~~~~~~~~~ */
function buildStrArg( arg ) {
var escQuote = &quot;\&quot;&quot;;
return escQuote +idStr +escQuote;
}
var el = document.createElement( &quot;div&quot; );
var input = &quot;<INPUT TYPE='BUTTON'&quot; +&quot;onclick='clk( this,&quot; +buildStrArg( idStr ) +&quot;)' />&quot;;
el.innerHTML = input;
document.body.appendChild( el );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top