The array data from the server is received through ajax and the buttons are created dynamically. How can I get the particular data for respective button when it is clicked.
For instance: if data from server is [‘a’, ‘b’, ‘c’], there are 3 buttons. When the 1st btn is clicked, it should pass ‘a’ in the click function and so on.
$.ajax({
url: urltest,
method: 'POST',
data: data,
success: function (response) {
var data = $.parseJSON(response);
$("#multiple_search_table").find("tr:gt(0)").remove();
$.each(data, function (index, value) { // how can I pass this individual value when the button is clicked.
$('#multiple_search_table').append('<tr><td>n' +
'<button class="search-value" data-dismiss="modal"> Select</button>n' + '</td></tr>');
});
},
});
How to get the respective data value in this function?
$(document).on('click', '.search-value', function () {
//how can I get the data for specific button?
});
Thanks in advance.
2
Answers
You can add another data attribute to the button element. Then you can access that data attribute on clicking the button.
Demo:
Update: Storing the object in the data-value attribute in the form of string and access each property by the key name:
You could use the
data-*
attribute:And PS: don’t use
.append()
inside loops for performance reasons. Append only once after the loop: