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

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.

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 issue on select option

need an help on a jquery script.
I have a select that trigger from Ajax a list of options available. Once user click this option if a variable got 1 a HTML div is added, if i change to another value HTML disappear. This script work as well first time: i click a option and div appear, when i click other option disappear but this cycle is completed if i it another time select option this stop working...
This is the code:
<script type="text/javascript">
$(document).ready(function() {
request_url = 'opzioni-select';
$.ajax({
url: request_url,
success: function(data){
$('#id_opzione').html("");
$.each(data, function(i, item){
var id = item.id;
var parent_id = item.parent;
var nome_opzione = item.nome_opzione;
var nome_parent = item.nome_parent;
$('#id_opzione').append('<option data-opzione="'+ item.nome_parent +'" data-parent="'+ item.parent +'" id="' + item.nome_opzione +'" value="' + item.id + '">' + item.nome_opzione +'</option>');
});
$(document).on('change', '.opzione', function(){
var parent = $('#id_opzione').find(':selected').data('parent');
var nome_parent = $('#id_opzione').find(':selected').data('opzione');
if(parent != null) {
$('#parent-div').append('<label for="parent-div" class=" control-label col-md-4 text-left">'+ nome_parent +'</label><div class="col-md-6"><input type="text" name="valore_parent" class="form-control"></div><div class="col-md-2"></div>');
} else {
$('#parent-div').hide('fast');
}
});
}
});
});
</script>
I tried to change div id in class and switched to "on('change" instead of call directly the #div with .change( but nothing.
Few problems - you're appending a bunch of options - then delegating for a class that i cant see being created.. Id recommend moving the delegated event to the document ready function. . and using the id of the select - and selecting the option after that using this.
<script type="text/javascript">
$(document).ready(function() {
request_url = 'opzioni-select';
$.ajax({
url: request_url,
success: function(data){
$('#id_opzione').html("");
$.each(data, function(i, item){
var id = item.id;
var parent_id = item.parent;
var nome_opzione = item.nome_opzione;
var nome_parent = item.nome_parent;
$('#id_opzione').append('<option data-opzione="'+ item.nome_parent +'" data-parent="'+ item.parent +'" id="' + item.nome_opzione +'" value="' + item.id + '">' + item.nome_opzione +'</option>');
});
});
$('#id_opzione').on('change', function(){
alert('Changed');
var parent = $('#id_opzione').find(':selected').data('parent');
var nome_parent = $('#id_opzione').find(':selected').data('opzione');
if(parent != null) {
$('#parent-div').append('<label for="parent-div" class=" control-label col-md-4 text-left">'+ nome_parent +'</label><div class="col-md-6"><input type="text" name="valore_parent" class="form-control"></div><div class="col-md-2"></div>');
} else {
$('#parent-div').hide('fast');
}
});
}
});
</script>

Set selected of a dynamic populated selectbox value ajax

I have a select element that populates another select on change. Everything works fine, but I want to automatically set the value of the new select to the first item in the array.
$.get($(this).data('url'), {
option: $(this).val()
}, function(data) {
var subcat = $('#models');
var options = " ";
subcat.empty();
$.each(data, function(index, element) {
options += "<option value='" + element.id + "'>" + element.name + "</option>";
});
subcat.append(options);
});
What I want to do is to set the selected value of models to first item.
Your option variable is just a string, and you can't append a string like that to the subcat object and have it turn into <option>s automatically.
Instead try one of these methods inside your $.each() function:
subcat.append($("<option value='" + element.id + "'>" + element.name + "</option>"));
or:
subcat.append($("<option/>").val(element.id).text(element.name));
The first option should be selected by default.
Fiddle

jQuery retrieve a value from a <ul> list

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);
});

$(this).attr("id") not working

as the title says, I keep getting "undefined" when I try to get the id attribute of an element, basically what I want to do is replace an element with an input box when the value is "other".
Here is the code:
function showHideOther(obj) {
var sel = obj.options[obj.selectedIndex].value;
var ID = $(this).attr("id");
alert(ID);
if (sel == 'other') {
$(this).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(this).css({
'display': 'none'
});
}
}
The HTML:
<span class='left'><label for='race'>Race: </label></span>
<span class='right'><select name='race' id='race' onchange='showHideOther(this);'>
<option>Select one</option>
<option>one</option>
<option>two</option>
<option>three</option>
<option value="other">Other</option>
</select>
</span>
It is probably something small that I am not noticing, what am I doing wrong?
Change
var ID = $(this).attr("id");
to
var ID = $(obj).attr("id");
Also you can change it to use jQuery event handler:
$('#race').change(function() {
var select = $(this);
var id = select.attr('id');
if(select.val() == 'other') {
select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
} else {
select.hide();
}
});
your using this in a function, when you should be using the parameter.
You only use $(this) in callbacks... from selections like
$('a').click(function() {
alert($(this).href);
})
In closing, the proper way (using your code example) would be to do this
obj.attr('id');
Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.
Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();
(function($) {
$.extend($.fn, {
showHideOther: function() {
$.each(this, function() {
var Id = $(this).attr('id');
alert(Id);
...
return this;
});
}
});
})(jQuery);
Not that it answers your question... Just food for thought.
What are you expecting $(this) to refer to?
Do you mean sel.attr("id"); perhaps?
Remove the inline event handler and do it completly unobtrusive, like
​$('​​​​#race').bind('change', function(){
var $this = $(this),
id = $this[0].id;
if(/^other$/.test($(this).val())){
$this.replaceWith($('<input/>', {
type: 'text',
name: id,
id: id
}));
}
});​​​
I had a similar issue.
`var ID = $(this).attr("id");`
sometimes using this method with arrow function (`
$('div).click(()=>{
console.log($(this).attr("id"))
}
`)
)Could result in undefined output so instead better using the keyword 'function'
In the function context "this" its not referring to the select element, but to the page itself
Change var ID = $(this).attr("id");
to var ID = $(obj).attr("id");
If obj is already a jQuery Object, just remove the $() around it.
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id to get the id of select tag.
You can do
onchange='showHideOther.call(this);'
instead of
onchange='showHideOther(this);'
But then you also need to replace obj with this in the function.

Categories

Resources