Home > OS >  jQuery: How to differ multiple same buttons and pass parameter?
jQuery: How to differ multiple same buttons and pass parameter?

Time:01-25

I try to move this working solution to jQuery.

<table>
    <tr th:each="l : ${lst}">
        <td>
            <input type="button" th:onclick="foo ([[${l}]])"/>
        </td>
    </tr>
</table>

....

function foo (x)
{
}

How can I do this the jQuery way? Is it a good idea to do so?

I tried this but I do not know how to get the parameter ${l} into the function also how to differ the differnt buttons.

<table>
    <tr th:each="l : ${lst}">
        <td>
            <input type="button" id="mybutton"/>
        </td>
    </tr>
</table>

...

$("#mybutton").click (function ()
{
});

CodePudding user response:

Fix your HTML to look like:

<table>
  <tr th:each="l : ${lst}">
    <td>
      <input  type="button" value="${l}">
      <!-- Fix the above's ${l} to be the desired output value -->
    </td>
  </tr>
</table>

Then in jQuery use:

function foo () {
  // Do something 
  console.log(this.value); // whatever is returned by `${l}`
};

$("table").on("click", ".mybutton", foo);

If you need some other text for the button other than ${l}, use a HTMLButtonElement:

<table>
  <tr th:each="l : ${lst}">
    <td>
      <button  type="button" value="${l}">Click me!</button>
      <!-- Fix the above's ${l} to be the desired output value -->
    </td>
  </tr>
</table>
  • Related