jQuery retrieve a value from a <ul> list - javascript

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><i class = "glyphicon glyphicon-user"> </i>' + payment_list.walkin_patient_name + '<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);
});

Related

on change after append new select2

I am using select2 and I want to handle on change event
it works well the first time, but when I append new select2 after every change and after appending new select2 on change does not work
$('select').on("select2:select", function(e) {
e.preventDefault();
var item_id = $("option:selected").data('id');
var product_id = $("option:selected").data('product');
$.ajax({
type: "post",
url: window.location.origin + '/product/get-items',
data: {
item_id: item_id,
product_id: product_id,
"_token": $('#csrf-token')[0].content //pass the CSRF_TOKEN()
},
success: function(data) {
$(".all-items").hide();
data.specifications.forEach(myFunction);
function myFunction(specification, index) {
var a = '<div class="all-items"><div class="mb-1"><div class="row py-1"><label style="font-size: 16px; margin: 10px; margin-bottom: 10px" class="py-1 mt-2">' + specification.name + ' :</label></div><div class="row"><select class="js-example-basic-single select-' + index + ' test' + index + ' item selectpicker selectItem" name="specification[]"> </div></div></div>';
$(".all").append(a);
specification.items.forEach(test);
function test(value, inx) {
if (data.itemIds.includes(value.id.toString())) {
var a = '<option style="font-size: 10px" data-id="e" data-product="dd" value="dd">' + value.name + '<span></span></option></select>';
$(".test" + index).append(a).select2();
}
}
}
}
});
});
I have to section for appending
first, append select2 and after this append options of each select
I want to use on change event for all select2 ( appending and initial )
the query selector $('select') collects only the current select elements in a document and not contains later elements appended to the document. So you need to use a more general selector to cover late elements. This should work:
$(document).on("select2:select","select",function(e) { })

jQuery Unable to remove multiple neighboring elements on AJAX Success

I am trying to figure out why I am unable to remove multiple neighboring elements on a successful ajax DELETE. When I had $(".file-preview").filter("a[href='" + fileLink + "']").remove(); by itself in the code below, I was able to remove the first link and when I add $(".remove-file").data("file-link", fileLink).remove(); after it, it breaks the first .remove() statement and removes all of the present .remove-file disregarding the value being passed to the data-file-link attribute in the link.
1) Why would the first remove be broken by this second remove?
2) Is there a better approach to what I'm trying to achieve which is to remove both neighboring elements on the click of .remove-file?
Here is an example of what the HTML looks like:
<div class="file-section>
<div class=" file-preview ">
https://test-bucket.s3.amazonaws.com/1/2017-01-30/screen-shot-2017-01-08-at-12.23.39-pm.png
<span class="glyphicon glyphicon-remove "></span>
</div>
<div class=" file-preview ">
https://test-bucket.s3.amazonaws.com/1/2017-01-30/screen-shot-2017-01-08-at-12.23.39-pm.png
<span class="glyphicon glyphicon-remove "></span>
</div>
</div>
jQuery:
$(document).on('click', '.remove-file', function(){
console.log('Delete Triggered');
var fileLink = $(this).data('file-link');
function pathExtract(url){
var fullUrl = url;
var delimiter = '/';
var start = 3;
var tokens = fullUrl.split(delimiter).slice(start);
var path = tokens.join(delimiter);
return path;
}
$.ajax({
url: '/app/sign?' + $.param({"file": pathExtract(fileLink)}),
type: 'DELETE',
success: function(){
console.log('This is the file link ' + fileLink);
$(".file-preview").filter("a[href='" + fileLink + "']").remove();
$(".remove-file").data("file-link", fileLink).remove();
},
error: function(error){
console.log('error ' + JSON.stringify(error));
}
});
});
.data("file-link", fileLink) isn't a filter, it sets the data of the elements selected. It simply returns the same collection it was called on, so when you call .remove() on the result it removes all the elements with the remove-file class.
If you want to remove just the elements with that data value, use .filter():
$(".remove-file").filter(function() {
return $(this).data("file-link") == fileLink;
}).remove();
This code:
$(".file-preview").filter("a[href='" + fileLink + "']").remove();
doesn't work because the a element is inside the .file-preview DIV, but .filter() tests if the element itself matches the filter. You should write:
$(".file-preview:has(a[href='" + fileLink + "'])").remove();
to test the contents.

Get values and ids of all span elements inside form

I am trying to get all span elements inside the form. The span elements are turning into input text fields and become editable. When you click away they are turning back into span elements. I will attached fiddle live example.
I gave it a go but the problem is that I am getting both ids but only value of the first span element.
Here is my html:
<span name="inputEditableTest" class="pztest" id="inputEditableTest" data-editable="">First Element</span>
<span name="inputEditableTest2" class="pztest" id="inputEditableTest2" data-editable="">Second Element</span>
<input id="test" type="submit" class="btn btn-primary" value="Submit">
And here is JavaScript with jQuery:
$('body').on('click', '[data-editable]', function () {
var $el = $(this);
var name = $($el).attr('name');
var value = $($el).text();
console.log(name);
var $input = $('<input name="' + name + '" id="' + name + '" value="' + value + '"/>').val($el.text());
$el.replaceWith($input);
var save = function () {
var $p = $('<span data-editable class="pztest" name="' + name + '" id="' + name + '" />').text($input.val());
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$("#test").on('click', function(){
var ok = $("span")
.map(function () {
return this.id;
})
.get()
.join();
var ok2 = $("#" + ok).text();
alert(ok);
alert(ok2);
//return [ok, ok2];
});
Here is the fiddle https://jsfiddle.net/v427zbo1/3/
I would like to return the results as an array example:
{element id : element value}
How can I read ids and values only inside specific form so something like:
<form id = "editableForm">
<span id="test1">Need these details</span>
<span id="test2">Need these details</span>
<input type="submit">
</form>
<span id="test3">Don't need details of this span</span>
Lets say I have got more than 1 form on the page and I want JavaScript to detect which form has been submitted and grab values of these span elements inside the form
I will be grateful for any help
$("#test").on('click', function(){
var result = {};
$("span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Here is an example: https://jsfiddle.net/v427zbo1/4/
Container issue:
You should use this selector: #editableForm span if you want to get all the divs inside this container.
$("#editableForm span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
But if you want to get only first-level children elements then you should use this selector: #editableForm > span
Example with getting all the spans inside #editableForm container: https://jsfiddle.net/v427zbo1/9/
If you want to have several forms, then you can do like this:
$('form').on('submit', function(e){
e.preventDefault();
var result = {};
$(this).find('span').each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Example with two forms: https://jsfiddle.net/v427zbo1/10/
You can't use .text to return the value of multiple elements. It doesn't matter how many elements are selected, .text will only return the value of the first one.
Virtually all jQuery methods that return a value behave this way.
If you want to get an array of values for an array of matched elements, you need another map. You also need to join the strings with , # as you're producing something along the lines of #id1id2id3 instead of #id1, #id2, #id3:
var ok = $("span").map(function () {
return this.id;
}).join(', #')
var ok2 = $("#" + ok).map(function () {
return $(this).text();
});
That said, you're already selecting the right set of elements in your first map. You pass over each element to get its ID, you already have the element. There is no reason to throw it away and reselect the same thing by its ID.
If I got you right following code will do the job
var ok = $("span")
.map(function () {
return {id: $(this).attr('id') , value: $(this).text()};
}).get();
Check this fiddle.

nextAll().remove() not working with dynamic added element in jquery

Here in my code i uses the jquery to load data from database with n-level performance .
But when i change the parent dropdown all next elements not going to remove please help.
Thank you in advance
$(document).ready(function() {
$(document).on('change', '#subcat', function() {
var id = $(this).val();
$(this).nextAll('.remove').remove();
var options = "<option value=0>--select subcategory--</option>";
$.ajax({
type: 'get',
url: '/category/' + id + '/dropDownDynamic',
success: function(responseText) {
if (responseText != "") {
$.each(responseText, function(index, value) {
options += '<option value=' + index + '>' + value + '</option>'
});
$('#subcatCustom').append('<div class="form-group marginRemove remove"><label class="col-sm-2 control-label">Select SubCategory:</label><div class="controls col-sm-5"><select name="parent" id="subcat" class="form-control">' + options + '</select></div></div>');
}
},
});
});
});
this line not working.
$(this).nextAll('.remove').remove();
Because they are not sibling of the current subcat element, they are siblings of current .remove so try
$(this).closest('.remove').nextAll('.remove').remove();
In your event handler this refers to the #subcat element, which is a descendant of .remove element, so we uses .closest() to find the .remove ancestor of this, then find that ancestor's next siblings
Note: ID of an element must be unique, so use subcat as a class instead of ID.

How to get the values in dynamicaly append check box list

I have created UI as the way what I want to enter data.
After selecting product name, flavors of that product append dynamically with check box.
All the check box data append dynamically using JS function. after that I tried to insert those data to database when button click. But I have problem in how to getting the ID of checkbox list which are checked.
Could any one please help me to figure out this problem?
I'm using Codeigniter framework for developing.
JS:
var ptype = $j("#cmb_freeproduct_type").val();
//alert(ptype);
//$j('#eqtyrw').hide(500);
$j.ajax({
type: 'post',
url: 'loadFlavorTypes',
data: {ptype:ptype},
success: function (data) {
alert(data);
var result = JSON.parse(data);
//alert(result);
var datas = [];
for (var x = 0; x < result.length; x++) {
datas.push('<tr id="'+result[x].product_flavour_id+'">'
+'<td>'
+'<input type="checkbox" name="fflavor_wise" id="fflavor_wise'+x+'" autocomplete="off" value=""></input>'
+'</td>'
+'<td id="fflavor'+x+'"> <b>'+result[x].product_flavour+'</b> </td>'
+'</tr>');
}
$j("#flavors_for_product_free").html(datas);
},
error: function(data){
alert('error');
}
});
jQuery:
// Find all checkboxes on the page that are currently checked.
var checked = $("input[type=checkbox]:checked");
Plain JavaScript:
// Find all input elements.
var inputs = document.getElementsByTagName("input");
var checked = [];
// Cycle our input elements list and find the checkboxes
// that are checked.
for ( var i = 0; i < inputs.length; i++ ) {
if ( inputs[i].type == "checkbox" && inputs[i].checked ) {
checked.push(inputs[i]);
}
}
In either case, you will now have an array containing checked checkboxes. Getting the ids of those should be pretty straight forward.
A strong argument for using jQuery when comparing these techniques.
It would be better to give them all a class (e.g. fflavor_wise_cb), then you can easily get the checked ones:
var checkedCbs = $('.fflavor_wise_cb:checked');
Or since they all share the same name, you can use that:
var checkedCbs = $('input[type=checkbox][name="fflavor_wise"]:checked');
Then you can iterate through them using each:
checkedCbs.each(function() {
console.log($(this).val());
});
In your code their value is empty, so to test better to give them a vale.
First, Please put dataType:"JSON" in ajax code, then use jquery $(data)each(function(index)){}
I have made above mentioned changes in your code, please check.
$.ajax({
type: 'post',
url: 'loadFlavorTypes',
data: {ptype:ptype},
dataType:"JSON",
success: function (data) {
alert(data);
var result = data;
//use jquery each function to iterate over the data
$(result).each(function(x){
$("#flavors_for_product_free").append('<tr id="'+result[x].product_flavour_id+'">'
+'<td>'
+'<input type="checkbox" name="fflavor_wise" id="fflavor_wise'+x+'" autocomplete="off" value=""></input>'
+'</td>'
+'<td id="fflavor'+x+'"> <b>'+result[x].product_flavour+'</b> </td>'
+'</tr>');
});
},
error: function(data){
alert('error with'+data);
}
});

Categories

Resources