I use this foreach:
foreach (var item2 in RItem.GetChildItems(item.ID_Ca))
{
<div id="@idc" class="accordion-collapse collapse" aria-labelledby="headingTwo2"
data-bs-parent="#accordionExample">
<div class="accordion-body" style="background: white; padding: 5px; padding-left: 20px;">
<button id="getthis" data-id="@item2.Name_Ca" type="button" onclick="Search()"
style=" color: #0028ff; font-size: 14px;">
@item2.Name_Ca
</button>
</div>
</div>
}
When the button is clicked, I want to send the data-id of the button to the controller through jQuery, the problem is that every time I click on the button, the only data that is sent to the controller is only the first record.
<script>
function Search() {
jQuery('.loading').fadeIn();
$.ajax({
url: 'SearchProjectsItems',
type: 'post',
datatype: 'json',
data: {
Cat: $(document.getElementById('getthis')).attr('data-id')
},
error: function (err) {
alert(err.Status + "" + err.StatusText);
}
}).done(function (data) {
$('#Search_CU').html(data);
jQuery('.loading').fadeOut();
});
}
</script>
I don't know what to do
$(document.getElementById('getthis'))
will always match the first button, right? Because as-is, all N of your Buttons will have that id. Maybe you should pass a unique id to theSearch
function or otherwise make sure you reference the correct button instance? Unfortunately, I don't use jQuery and cannot tell, what would be the canonical way to do that.data-id
that corresponds to the button in theSearch
function. Try addingonclick="Search(this.data-id)"
and change your function asSearch(data-id)
and pass that in your Ajax request.Search()
which looks up an element and reads one of its properies. Why not pass the value of that property as an argument to the function to begin with?