skip to Main Content

I’m trying to add a function call in an onclick event to the data being returned. I haven’t been able to figure out if I’m missing quotes anywhere. Could you provide any insight the correct to do this?

the_data = "<a onclick=popup_manager.getFormPopUp(" + options + ")>"+the_data+ "</a>";

3

Answers


  1. Did you want something like this?

    var div=document.getElementById("myDiv");
    var element="<a onclick=foo()> Click Me</a>";
    
    div.innerHTML+=element;
    
    function foo(){
      console.log("Clicked..:)");
    }
    <div id="myDiv">
    
    </div>
    Login or Signup to reply.
  2. You need to wrap the value you use in the arguments of your function in quotes which are escaped from the body of the string which contains them:

    const options = 'foo';
    let the_data = 'bar';
    the_data = '<a onclick="popup_manager.getFormPopUp('' + options + ''")>' + the_data + '</a>';
    console.log(the_data);

    Improving this approach, you could use a template literal to make the syntax less messy and avoid the need to escape the inner quotes:

    const options = 'foo';
    let the_data = 'bar';
    the_data = `<a onclick="popup_manager.getFormPopUp('${options}')>${the_data}</a>`;
    console.log(the_data);

    To take this another step further, you could follow best practice and remove the outdated inline onclick attribute, which should be avoided, and instead attach your event handlers unobtrusively, providing the arguments to the handler function through data attributes in your HTML:

    const options = 'foo';
    let the_data = 'bar';
    the_data = `<a href="#" data-options="${options}">${the_data}</a>`;
    
    const container = document.querySelector('#container');
    container.innerHTML = the_data;
    
    container.querySelector('a').addEventListener('click', e => {
      console.log(e.target.dataset.options)
    });
    <div id="container">sdfsdf</div>
    Login or Signup to reply.
  3. you can use document.createElement to get the result you wanted

    let a = document.createElement("a");
    a.innerHTML = the_data;
    a.onclick = popup_manager.getFormPopUp(options);
    

    then append ‘a’ to your html document

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search