I have the following script that creates a list of names :
setInterval(function() {
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>cashier/walkin_patient_payments",
dataType: "JSON",
success: function(payment_list) {
pat_payment_list = $('#walkin_patient_payment').empty();
if (payment_list === null) {
} else {
$.each(payment_list, function(i, payment_list) {
pat_payment_list.append('<li><a href="#walkin_patient_form" id="walkin_payment_link" class="walkin_payment_link"><i class = "glyphicon glyphicon-user"> </i>' + payment_list.walkin_patient_name + '</a><span style="color:red !important;"> Kshs : ' + payment_list.amount + '</span>\n\
<input type="hidden" id="walkin_id_list" name="walkin_id_list" class="walkin_id_list" value="' + payment_list.walkin_id + '"/>\n\
</br></li>');
});
}
},
error: function(data) {
//error do something
}
});
}, 3000);
Which is appended to the following UL list :
<ul class = "dashboard-list walkin_patient_payment" id="walkin_patient_payment">
</ul>
But when I try to run the following script that is supposed to pick individual walkin id from the list it only gives the value of the first list even when I click the number 5th list.
Below is the script :
$('.walkin_patient_payment').on('click', '.walkin_payment_link', function() {
//get
var walkin_id = $(this).closest('ul').find('input[name="walkin_id_list"]').val();
alert(walkin_id);
});
What is the best way to implement this? What am I doing wrong?
That is because you are traversing to ul element and .find('input[name="walkin_id_list"]')
will return all the inputs with name walkin_id_list
in ul. and using .val()
on collection of elements will only return the value of first element.
You need to use .closest('li')
instead of .closest('ul')
:
var walkin_id = $(this).closest('li').find('input[name="walkin_id_list"]').val();
Also note that you are generating the elements with same ids. IDs should always be unique. You can rather use same class instead.
You can implement click directly on li
$('.walkin_patient_payment li').click(function () {
var walkin_id = $(this).find('input[name="walkin_id_list"]').val();
alert(walkin_id);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.