SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2005
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dyanmically set function name and arguments to .onclick

    Hi,

    I'm trying to build some HTML on the fly using javascript. Part of this is an input button, for which the onclick event needs to be set to a javascript call and some arguments, both of which are set dynamically.

    I started out trying this:
    Code:
    strHTML = "<input type='button' value='clickMe' onclick='" + fnName + "(" + params + ") >";
    myElements.innerHTML = strHTML
    But this doesn't work because for some bizarre reason innerHTML scrambles my HTML string into unusability - it puts the onclick first and then fails to write the end bracket.

    I tried to work out what innerHTML was doing and came across a couple of other examples of the same problem but no solutions.

    So I figured I'd do it the long way round and write the DOM:
    Code:
    eButton = document.createElement("input");
    eButton.setAttribute("type", "button");
    eButton.setAttribute("value", btnText);
    eButton.onclick = function() { functionName + "(" + params + ")" };
    InlinePopUpArea.appendChild(eButton);
    But that doesn't work because "functionName" is treated as a literal, not a variable.

    This doesn't work either:
    Code:
    eButton.setAttribute("onclick", functionName + "(" + params + ")");
    Neither does this:
    Code:
    var fnCallText = "function() { " + functionName + "(" + params + ") };";
    eButton.onclick = fnCallText;
    Any suggestions as to how I can get this done? I'm not above using innerHTML if I can work out why it's scrambling my string and stop it!

    Cheers,
    Matt

  2. #2
    SitePoint Enthusiast
    Join Date
    Nov 2005
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can be done by using eval:

    eButton.onclick = function() { eval(fnCallText) };


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •