Get button id dynamically

I need to get the id of the button when I click ---

This is my code for my button to dynamically dynamically display data when the condition is true.

Twig:

{% for usr in userstats %} {% if usr.condition == TRUE %} <button type="submit" class="btn btn-success btn-xs myOnButton.onclick = function(event){alert(event.currentTarget.id);} myOnButton">Allow</button> 

this is my ajax for my button ---

 <script> $(".myOnButton").on('click', function () { if (confirm('{% trans %}Are you sure?{% endtrans %}')) { $('body').addClass('load'); var url = '/hello/hello'; // Submit data via AJAX var data = {}; $.ajax({ url: url, type: 'POST', success: function (data) { // Redirect to view url = '/hello'; location.href = url; } }); } return false; }); 

To make it clearer: suppose we have in one column (name: Dell, CompanyId: 3001, Address- HelloDell, Phone-07555, condition: True), and in the other column we have (name: Apple, CompanyId: 5001, Address- HelloApple, Phone-07555, condition: True).

So, how can I get CompanyId when a button is clicked in a twig file?

Does anyone know any solution to this problem?

+4
source share
1 answer

using simple JS (without frameworks), and if you have several buttons with the myOnButton class, you can easily do this:

 var buttonClickHandler = function(e){ console.log(e.target.id); } var buttonList = document.getElementsByClassName('myOnButton'); buttonList.forEach(function(button){ button.addEventListener('click', buttonClickHandler); }); 

EDIT1 and EDIT2:

using jQuery I assume that the corresponding code would look something like this:

 $('.myOnButton').on('click', function(e){ var buttonId = e.currentTarget.id; //start post request $.post('my/path/to/service.php', {id:buttonId}, function(data, err){ //wait for response here console.log("my data yippii", JSON.stringify(data)); }) }); 

PHP Part service.php will look something like this (I have to admit this is absolutely not my strength)

 //retrieve id id = $_POST['id']; 

Now that you have the identifier, you can check it and start SELECT on the DB or something

hope this helped

+2
source

All Articles