execute command to new loaded content from ajax jquery - javascript

I got some problem with jquery.
<select class='my-select' id='exist_select'></select>
<div id='target'></div>
<script>
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select = '<select class="my-select" id="select'+data[key]+'"></select>';
}
$('div#target').html(select);
$('.my-select').append($('<option>', {
value: 100,
text: 'Added option',
}))
})
})
</script>
The selects was successfully loaded. As you see, I tried to make HTML selects. Then append spesific option manually for each select.
Unlucky, It doesn't work. But it works on #exist_select.
I have no idea. Please help me.

First wrap your code in a document ready statement, second your loop only gets the first element, you need to use concatenation to append the rest,3th you can append the option directly in the select:
$(function(){
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select += '<select class="my-select" id="select'+data[key]+'"><option value="100">Added option</option></select>';
}
$('div#target').html(select);
})
})
})

Event listeners can only be attached to elements that are in the DOM, not elements that don't exist at the time.
For dynamically created elements, you need to use the .on function:
$('body').on('change', '.my-select', function(){
alert('here');
});

Related

row().data to retrieve a specific column row using datatables.net plug-in

EDIT: Deleted my YouTube Video, here is simple solution:
$(document).on('click', '.edit_btn', function() {
var rowData = $('#example').DataTable().row($(this).parents('tr')).data();
});
"Working Code":
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
$.ajax({
url: 'index.php',
datatype: "json",
data: { edit_id : edit_id },
async: false,
success: function(result) {
//alert(edit_id);
$("#edit_id").val(edit_id);
} //success func
}); //ajax
}); //end ready
</script>
What I tried
I tried many things as in the youTube video. I could not get the original example to work on the link.
Should I use Jquery like this??
var last_name = $('#example').DataTable().row( last_name ).data();
Or php like this?
$('#editLastName').val( <?php echo $row['first_name']; ?> );
Or something within the ajax file?
What you could try is to get the parent tr element, although I'm not sure if that's the best approach.
Simplified:
$(document).on('click', '.edit_btn', function() {
var rowData = $('#example').DataTable().row($(this).parents('tr')).data();
});
Basically you get the parent tr from the button element you click on and get the data from that row.
What I also noticed, your data-id from the button seems messed up. It looks like this: data-id='s-"0"'. I'm not sure how you generate this, but in case you fix that and it looks like data-id="0" you can select rows with $('#example').DataTable().row($(this).data('id')).data();.
As you can see, there are quite a few possibilities here.

AJAX request only executes on one checkbox, need it to execute on any

I have the following code, checkboxes are being generated by php based on the number of objects. There is one checkbox per object, and the code in the foreach that generates these is as follows (NOTE: this part is working fine, my problem is below):
"<input type='checkbox' name='markAsUnread' id='markRead' value='$sms->id' class='markAsUnread'>",
Here is the jQuery script that I am trying to use to mark any of the "clicked" boxes as "read". This particular script works when the first box is clicked at any time, but I need it to work for any of the boxes clicked (second, third, etc). I only need it to work on one at a time, but I need it to do so with any one selected.
<script type="text/javascript">
var myEl = document.getElementById('markRead');
myEl.addEventListener('click', function() {
var bloop = $('#markRead').val();
$.ajax({
type: 'POST',
url: '/link/to/route',
data: {sms: bloop},
success: function(data) {
window.location = '/foo/bar';},
contentType: "application/json",
dataType: 'json'
});
}, false);
</script>
I assume that it is not working because it is only grabbing the first box, so what needs to be changed to make it work with any of the selected checkboxes?
That should not work. If you repeatedly create elements with the same id, you violate html rules. There can only be one.
Instead of applying the function to only one element, identified with an ID, as
var myEl = document.getElementById('markRead');
ask for all elements with the name "markRead":
var myElements = document.getElementsByName('markRead');
which gives you an array to iterate over.
Additionally change your jquery-selector from
$('#markRead')
to
$("[name=markRead]")
Also, make sure that id-values are actually unique within one html document.
try following script and check
<script type="text/javascript">
$(function(){
var myElements = $('input[name=markAsUnread]');
myElements.click(function() {
var bloop = $('input[name=markAsUnread]:checked').val();
$.ajax({
type: 'POST',
url: '/link/to/route',
data: {sms: bloop},
success: function(data) {
window.location = '/foo/bar';},
contentType: "application/json",
dataType: 'json'
});
}, false);
});
</script>
Also, remove ID attribute from your generated checkboxes or make it Unique instead of having same value for all elements.
So I solved it, iterating over the elements and adding a click listener within the iterator seemed to do the trick:
$(function(){
var myElements = document.getElementsByName('markAsUnread');
$.each(myElements, function (index){
$(this).on("click", function(){
$.ajax({
type: 'POST',
url: '/foo/bar',
data: {sms: $(this).val()},
success: function(data) {
window.location = '/back/home';},
contentType: "application/json",
dataType: 'json'
});
});
});
});
I also removed IDs from the PHP generated checkboxes, as I wasn't using them.

How to refresh select option list after AJAX response

I use fastSelect plugin http://dbrekalo.github.io/fastselect/
I have input tag, when change value i do a call ajax to php server.
My problem is that When I inspect the item and I look in the options, I see the data I just added, but in the browser it does not display, sorry for the quality of my English
any help please ?
Enclosed my code
<select id="Recherche_log_commune" name="Recherche[log_commune][]" class="multipleSelectDepCom" multiple="multiple">
<optgroup label="Communes">
</optgroup>
</select>
<script> $('.multipleSelectDepCom').fastselect({maxItems: 10,noResultsText: 'Pas de résultat'}); </script>
<script>
$("#leftBlockDashboard .fstQueryInput").on("change paste keyup", function(event) {
event.preventDefault();
getCommuneAndDepartement($(this).val());
});
function getCommuneAndDepartement(expression) {
var dataString = {expression: expression};
$.ajax({
url: '{{path('get_commune_departement')}}',
type: "POST",
data: dataString,
success: function(data){
$("#Recherche_log_commune").find('optgroup[label="Communes"]').empty();
$.each(data, function(){
var option = '<option value="'+ this.com_id +'">'+ this.com_libelle +'</option>';
$("#Recherche_log_commune").find('optgroup[label="Communes"]').append(option);
});
$('.multipleSelectDepCom').fastselect({
maxItems: 10,
noResultsText: 'Pas de résultat',
});
}
})
}
</script>
ok solved , very rude but works ... on ajax callback here is what i do:
1) get a reference to original node ...
in my case it is
var cc = $('#categories');
2) check if .fstElement exists
var fsexist = $(".fstElement").length > 0;
3) if exists remove it and reappend the original node
if (fsexist) {
$('.fstElement').remove();
$('#categories_div').append(cc);
}
4) reinit fastselect
$('#categories').fastselect({maxItems: 10,
noResultsText: 'Choose categories'});
You will need to reattach the control after the options are loaded:
$('.selector').fastselect();
Even more complicated (to keep the selected value):
$('.selector').fastselect({
onItemSelect: function($item, itemModel) {
//load your stuff
$('.selector').fastselect();
}
});
You Will need to refresh the select2 after ajax call like this.
setTimeout(function(){
$('#select2_id').fastselect();
},500);

How to apply the .change function on the field which is created b the .change function of some other field?

This function is creating a process name(prc) field on changing part no(pno) field, now i want the process characteristic field on changing process name but .change function on process name is not working($('#prc').change(function(){}); this function is not working)
$('#pno').change(function(){
var partno=$("#pno option:selected" ).val();
$.ajax({
cache: false,
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array('controller'=>'Partconfs','action'=>'addpro'));?>',
data: ({partno:partno}),
success: function(result){
var pch=result.split('//');
var plen=pch.length;
var str="";
$('#fid').html('');
str='<tr><td><br><b>PROCESS NAME</b><br><br></td></tr><tr><td><select name="process_name" label="" id="prc" style="height:30px; margin-top:-5px; min-width:190px; width:auto;" ><option value="">Select any</option>';
$.each(pch,function(i,v){
str += '<option value="'+v+'">'+v+'</option>';
});
str +='</select></td></tr>';
$('#fid').append(str);
}
});
});
You either need to add the event listener directly after this line:
$('#fid').append(str);
when the node is ready to have event listeners attached, or you need to delegate the event from a parent node that is available before your new <select> is written to the DOM.
$('#fid').on('change', '#prc', function() {
// do your stuff
});
This works by attaching the event to a valid component, but only firing when the selector of the changed element (beneath #fid) matches the selector '#prc'
You have to use the on function on dynamic fields.
http://api.jquery.com/on/

jQuery select every time first element

HTML:
<div class="vote" id="<?php echo $id; ?>">
jQuery:
$('.vote').on('click', function() {
var div = $(".vote").attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(".vote").attr('id')
},
success: function(data) {
alert(div);
}
});
});
this works, but div var it's always first element - and runs twice (two divs with vote class).
I use AJAX for displaying results (divs with vote class) also.
Why is this happening and how can I fix?
You need to use this, which refers to element which invoked the element.
var div = $(this).attr('id'); //this.id;
When you are using $(".vote").attr('id') it will always return you id of first element.
As you are using id to store custom data. I would recommend you to use data-* prefixed custom attribute which can be fetched by using .data()
<div class="vote" data-id="<?php echo $id; ?>">
Then you can use
var id = $(this).data('id');
You need to use current elements clicked context this:
var div = this.id;
Replace your $('.vote') to $(this) like this below:
$('.vote').on('click', function() {
var div = $(this).attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(this).attr('id')
},
success: function(data) {
alert(div);
}
});
});
Use this.id instead of $('.vote').attr('id'), because javascript will get the first id he founds if you use $('.vote').attr('id')

Categories

Resources