Problems with jQuery onchange on ios - javascript

I'm having problems with the jQuery onchange event not working in Safari on my iPhone.
This is where the onchange is:
//Detects change in location and updates with location name and address
$('#location').on('change', function () {
var serviceId = $("#location").val();
$.ajax({
type: "get",
url: 'utilities/fetchdata?fetch=locationbyid&location=' + serviceId + '',
success: function (data) {
var locationData = JSON.parse(data);
document.getElementById("location-name").innerHTML = locationData.name;
document.getElementById("location-address1").innerHTML = locationData.address;
//Fetch servies offered by that location
$.ajax({
type: "get",
url: 'utilities/fetchdata?fetch=services&location=' + serviceId + '',
success: function (data) {
console.log(data);
var newOptions = JSON.parse(data);
var $el = $("#service");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
}
});
});
This is what it is listening on:
<select name="location" class="form-control" id="location">
<option disabled selected>-- Velg Lokasjon --</option>
<?php
//Fetch locations
if (! $locations = $locationData->fetchHTMLINPUT()) {
echo $locations;
} else {
echo "<option disabled>Systemfeil oppsto</option>";
}
?>
</select>
What I need it to do is fire the event consistently as this is where it fetches the next step for the user to follow.
Expected behaviour:
Fetch the next input fields for use in the select
What I think is weird is that it works in Chrome on my desktop as well as Edge.
Could anyone point me to a workaround for use on mobile?

Okay,
I kinda figured it out. Seems like mobile iOS browsers can't refresh the contents of a select after the HTML has been rendered, but changing the HTML using f.ex $('#service').html(data); works like a charm, though the HTML has to be generated server side.

Related

Refresh the select dropdown data upon selecting using Ajax in Laravel 5.4

Hi i have this select dropdown in Ajax pass the data to the server then display to my select dropdown. The code works very well. Now my problem is i want that upon selecting the data the other select dropdown will refresh base on the selected one. Here is my Ajax code below
$("#util").change(function(){
const util = $(this).children("option:selected").val();
//make ajax call
$.ajax({
type: "GET",
url:'/dno-personal/get-data/' + util,
data:{
_method: 'get',
"id":util
},
success:function(data){
var docu = $('#docu');
console.log(data);
data.forEach(function(val, index){
console.log(val.document_name);
docu.append(
$('<option></option>').val(val.document_name).html(val.document_name)
);
});
},
error:function(data){
console.log('Error:', data);
}
});
});
my html select
<div id="documentList" class="col-lg-2">
<label>Document List</label>
<select id="docu" name="" class="selcls form-control">
</select>
</div>
my process in server in php
//
public function getData($id){
$getDocuments = DnoPersonalUtility::where('pu_id', $id)->get()->toArray();
return response()->json($getDocuments);
}
Can someone help me figured this thing out? Tia
function run() {
var e = document.getElementById("ddlViewBy");
var id = e.options[e.selectedIndex].value;
$('#pt_iddd').val(id);
$.ajax({
url:"<?php echo $link_url; ?>data/customer.php",
method:"POST",
data:{query1:id},
success:function(data3){
document.getElementById("fee").innerHTML=data3;
}
});
}
$(document).ready(function(){
$("#ddlViewBy").click(function(){
var query = $('#pt_iddd').val();
if(query != ''){
$.ajax({
url:"<?php echo $link_url; ?>data/details.php",
method:"POST",
data:{query:query,i:"da"},
success:function(data){
$('#mySelect').html(data);
}
});
}
});
});
<select class="form-control" onchange="run()" id="ddlViewBy">
have your option code here
</select>
<select class="form-control" id="mySelect">
</select>
This is the script I used
In this case, first, select the value on the basis of which you want your second dropdown values to be changed via var id = e.options[e.selectedIndex].value; then on click of your first dropdown post that value to ajax and as per your code appends the value to your second dropdown.

Too many ajax calls when form selections change

My webpage has two main sections: (1) search criteria (selection boxes in a form) used to access database information, and (2) a div in which the results are displayed. When the page loads initially, default values in the form are serialized and sent via ajax to php and the results are rendered. This results section is paginated to display all the results by clicking next, previous, etc. This all works perfectly.
Here’s the problem: each time the user makes a change to the criteria and the form’s data is serialized and sent via ajax, another layer of results is added somehow. When paginating through the results, it processes page 2 for each of the “layers” but only the last one that arrives from the server is displayed on the webpage. So, every time another change is made, another layer is added. Since ajax is asynchronous, the results displayed may or may not be the correct “layer.”
HTML:
<form id='submitCriteria' action='' method='post'>
<select id='selLevel' class='selectpicker' name='levels'>
<option title='Levels' value='No Preference'
selected = 'selected'>No Preference</option>
<option title='Levels:<br> 1+' value=1 >1+ </option>
<option title='Levels:<br> 2+' value=2 >2+ </option>
<option title='Levels:<br> 3+' value=3 >3+ </option>
</select>
</form>
<!-- Pagination: -->
<div id="spinnerDet" class="spinnerA">
</div>
<div id="paginationdiv">
<div id="pagination_container">
<div class="pagination">
<ul><li class="inactive">Previous</li>
<li class="pagerange">
<span class="total" a=" 58">
Page 1 of 58 </span></li>
<li p="2" class="active">Next</li>
</ul>
</div>
<!-- Output from server: -->
<table>
<tr><td>Levels</td><td>3</td></tr>
</table>
</div>
</div>
javascript/jQuery:
$("#submitCriteria").change(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'post',
data: $("#submitCriteria").serialize(),
url: "/load_plans.php",
success: function(data) {
paginateDetails (data)
},
});
return false;
});
function paginateDetails (data) {
selDetails = JSON.parse(data);
var levels = selDetails.levels;
var totalsline = "Number of levels: " + levels;
$('#numResults').removeClass('spinnerA');
$('#numResults').addClass('stop-spin');
$('#numResults').html(totalsline);
loadData(1); //initial output based on default values
// Pagination buttons event:
$('#paginationdiv').on('click touchend',
'#pagination_container .pagination li.active', function (e) {
e.stopPropagation();
e.preventDefault();
var page = $(this).attr('p');
loadData(page);
});
function loadData(page) {
$.ajax({
type: "POST",
data: eval("'page=' + page + '&levels=' + levels"),
url: "loadDetails.php",
success: function (msg) {
$("#pagination_container").ajaxComplete(function (event, request, settings) {
$("#pagination_container").html(msg);
});
}
});
}
}
How do I eliminate another “layer” when selections in the form are changed/updated?
I think the problem is with the structure of your code, in this case you shouldn't be nesting the functions. Also you are repeatedly attaching click event to #paginationdiv (does it get removed and reatached when you reload data? You should use class instead of div in that case).
Without trying the code, i believe your problem might be caused by your loadData function - in your success callback you don't need to hook ajax complete again, success is called when your request is complete and successfull. I believe that part of your code was triggering twice ( on success and when ajaxComplete fired)
Your refactored code should look something like this:
$("#submitCriteria").change(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'post',
data: $("#submitCriteria").serialize(),
url: "/load_plans.php",
success: function(data) {
paginateDetails (data)
},
});
return false;
});
function loadData(page) {
$.ajax({
type: "POST",
data: eval("'page=' + page + '&levels=' + levels"),
url: "loadDetails.php",
success: function (msg) {
//$("#pagination_container").ajaxComplete(function (event, request, settings) {
$("#pagination_container").html(msg);
//});
}
});
}
function paginateDetails (data) {
selDetails = JSON.parse(data);
var levels = selDetails.levels;
var totalsline = "Number of levels: " + levels;
$('#numResults').removeClass('spinnerA');
$('#numResults').addClass('stop-spin');
$('#numResults').html(totalsline);
loadData(1); //initial output based on default values
// remove previous click handlers
$('#paginationdiv').off()
// Pagination buttons event:
$('#paginationdiv').on('click touchend',
'#pagination_container .pagination li.active', function (e) {
e.stopPropagation();
e.preventDefault();
var page = $(this).attr('p');
loadData(page);
});
}

execute command to new loaded content from ajax jquery

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

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

JS Create delay on Select Drop-Down Menu Open

I have a drop-down menu that lists subjects. I am loading those subjects via an AJAX call. The subjects load properly, they just don't load fast enough to populate the select menu until AFTER the menu has been opened. This causes the user to need to open the menu, close the menu, then open it again.
How can I cause a delay on the drop-down-menu open to give the response enough time to populate the drop-down menu? Thanks for any and all help.
Code:
Drop-down Menu
<div id="subjectForm" class="form-row">
<label>1) Subject Selection:</label>
<select name="subject" id="subjectSelect" class="input-medium">
<option value="0">All</option>
</select>
</div>
AJAX Call
document.getElementById("subjectForm").addEventListener("click", function( event ) {
var selectCount = $('#subjectSelect option').size();
if(selectCount == 1) {
$.ajax({
url: '/v2/subjects?',
method: 'GET',
data: {'core': number},
success: function (data) {
// Populates the $subjectSelect filter with subjects
// For each grade brought back from response, add it to the grade filter
$.each(data, function(i, subject){
$('#subjectSelect')
.append($('<option></option>')
.attr("value", subject.id)
.text(subject.title));
});// each
}// success
});// ajax
}// end if
}, false);// #subjectForm clicked
Since the number value is defaulted, I would change the load to happen on document ready, rather than waiting until the click event.
$(document).ready(function () {
var loadSubjectSelect = function(){
var selectCount = $('#subjectSelect option').size();
if(selectCount == 1) {
$.ajax({
url: '/v2/subjects?',
method: 'GET',
data: {'core': number},
success: function (data) {
// Populates the $subjectSelect filter with subjects
// For each grade brought back from response, add it to the grade filter
$.each(data, function(i, subject){
$('#subjectSelect')
.append($('<option></option>')
.attr("value", subject.id)
.text(subject.title));
});
}
});
}
};
loadSubjectSelect();
})();
Then when you add the other menu, you can call loadSubjectSelect() on its click event.
Render options after some seconds
success: function (data) {
// Populates the $subjectSelect filter with subjects
// For each grade brought back from response, add it to the grade filter
var myoptions = "";
$.each(data, function(i, subject){
myoptions += "<option value='"+subject.id+"'>"+subject.title+"</option>";
});
$('#subjectSelect').html(myoptions);
}
Hope it solves the problem.

Categories

Resources