Home > front end >  Append id from button clicked to an existing JQuery Function that Toggles a Form
Append id from button clicked to an existing JQuery Function that Toggles a Form

Time:06-17

I have a table, each row is ended with a dynamically generated button. That button has an id matching the id of the user from the DB. I want to be able to press any of the buttons and pass that id to a script that toggles a form. I just cannot work out how to append the id to an existing script to toggle the form.

So far the code I have is

<button type='submit' class='btn btn-success' id='formButton$uid' onclick='myFunction()'>Edit User #$uid</button>

&

$(document).ready(function() {
        $("#3").click(function() {
    $("#form1").toggle();
  });
});

As you see in the code above I have hard coded the id of 3 in but as I say I am looking for that id to take the value, the id, from any of the buttons clicked so if there are 50 buttons they can all toggle the form as the button clicked id will have be appended into the JQuery toggle function.

CodePudding user response:

After a few hours I have managed to add the id to the JQuery.

     <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
        <input type="submit" name="mybutton" id="1" value="1">
        <input type="submit" name="mybutton" id="2" value="2">
        <input type="submit" name="mybutton" id="3" value="3">
        <input type="submit" name="mybutton" id="4" value="4">
    </form>

Then the JQuery

$(document).ready(function() {
  $("#<?php echo $_POST['mybutton'] ?>").click(function() {
   $("#form1").toggle();
 });
});

I don't know if this is the best way of doing the job?

CodePudding user response:

you could hook the on click event on the element name like so

<button type='submit' name="mybutton" Id="#$uid" onclick='myFunction()'>Edit User #$uid</button>
<button type='submit' name="mybutton" Id="#$uid" onclick='myFunction()'>Edit User #$uid</button>
<button type='submit' name="mybutton" Id="#$uid" onclick='myFunction()'>Edit User #$uid</button>
$('button[name="mybutton"]').each(function() {
  $(this).click(function() {
    console.log($(this).attr("Id"));
    $("#form1").toggle();
  });
});

[https://jsfiddle.net/bjq5drwh/2/]

I hope this helps

  • Related