skip to Main Content

I have the following jquery/Javascript code which creates a new button on the screen

$("#prefixed-list").append(`
<li class="list-group-item d-flex my-auto mx-auto border-0" order="9999999999">
  <button type="button" class="btn btn-info mt-3" onClick="prefixCall(urlDomain, searchContent, offset)">Load More</button>
</li>
  `);

urlDomain, searchContent, offset are all variables defined in the same function. Currently when the button gets created on the page

<button type="button" class="btn btn-info mt-3" onclick="prefixCall(urlDomain, searchContent, offset)">Load More</button>

I want it to have the value of the variables. How can that be done?

2

Answers


  1. You can add event handler on(eventname,[eventData], callback). This allow to listen the events from the elements you append dynamically.

    You can like this:

    $("#prefixed-list").append(`
      <li class="list-group-item d-flex my-auto mx-auto border-0" order="9999999999">
        <button type="button" class="btn btn-info mt-3" id="prefixed-list-btn">Load More</button>
      </li>
    `);
    urlDomain="asdf", searchContent="asdf", offset="asdf"
    $("#prefixed-list-btn").on("click", {urlDomain, searchContent, offset}, (ev)=>{prefixCall(ev.data.urlDomain, ev.data.searchContent, ev.data.offset)});
    
    function prefixCall(urlDomain, searchContent, offset) {
      console.log(urlDomain, searchContent, offset);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <ul id="prefixed-list"></ul>

    Best regards,
    Bogdan Bob.

    Login or Signup to reply.
  2. since you’re already using template literal, ${urlDomain} etc

    const urlDomain="this is the urlDomain";
    const searchContent = "This is searchContent";
    const offset = "guess what this is";
    const prefixCall = (...args) => console.log(args);
    $("#prefixed-list").append(`
    <li class="list-group-item d-flex my-auto mx-auto border-0" order="9999999999">
      <button type="button" class="btn btn-info mt-3" onClick="prefixCall('${urlDomain}', '${searchContent}', '${offset}')">Load More</button>
    </li>
      `);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul id="prefixed-list"></ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search