JS Create delay on Select Drop-Down Menu Open - javascript

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.

Related

Problems with jQuery onchange on ios

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.

Submit form elements within a table as ajax request?

I have a dynamically generated table with an edit and delete button within each row, when a user edits inputs, checkboxes, and textareas, clicks edit, I need to post values to a processing page
How to send ajax request that contains form elements that are in html table this (row) or specific row, or this iteration only row?
Please help I'm not that good at js
//First of all thank you.
//After a deep search, I solved my own problem, here's the answer
// if anyone has encountered the same thing:
<script>
$('.editRow').on('click', function (e) {
var data = {};
var row = $(this).closest('tr');
var rowData = row.find('input, checkbox, textarea');
if (rowData.length > 0) {
rowData.each(function () {
data[$(this).attr('name')] = $(this).val();
//rowData.push($(this).val());
});
//data=dataRow
}
$.ajax
({
method: 'post',
url: 'tbl_process.php',
data: {
data: data
},
success: function (data) {
$('#content').html(data);
}
});
});
</script>

How to detect that my select form have been change by ajax success

I have two form input ( text and select form ).
The select form change by ajax success when user search the employee data.
Now, i want the other jquery function that can automatically detect when the select form have been change by ajax success and retrieve the new value of select form to use by other function to make new data in my input text.
my Search Employee Function
function search_personal_result(formObj, urlres, responseDIV, disable_data, modal_class,result_data)
{
disable_data=disable_data||false;
modal_class=modal_class||false;
result_data=result_data||false;
var loading = '<p>Loading ...</p>';
$.ajax({
url: site_url+'/'+urlres,
beforeSend: function(){
$(responseDIV).html(loading);
},
data: $(formObj).serialize(),
type: "post",
dataType: "html",
success: function(response){
//proceed data result here
if(result_data==false){
var obj = jQuery.parseJSON(response);
$.each(obj, function (index, value) {
if(result_data==false){
for(var j in value){
//My SELECT Form Changed here
$('#VCIDSBU').val('MY NEW VALUE');
}
}
});
}
},
error: function(){
alert("Terjadi kesalahan!");
},
});
}
If the user search the employee data using search_personal_result, my select form have been successfully changes.
Now that i need is, how to make the other jQuery function that can detect that my SELECT Form have been changed by search_personal_result
I have try using
$(function () {
$('#form_create_sp').on('change','SELECT#my_select_id',function(){
alert('it changes');
});
})
It can only detect when the user manually change the select form. but not working when the select form changed by search_personal_result
Thanks for all expert here
You could always do some sort of console.log("Success"); Function based on if it sent or not.

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

AutoComplete not working on the Search Box using Jquery

I am trying get get TypeAhead functionality on a search textbox. I have 2 radio buttons on the form if one of them is selected I need the type-ahead functionality to add the ist of masters to the search box.
//html
<li> #Html.TextBox("SearchTitle") </li>
//JavaScript
if ($('input[name=SearchType]:checked').val() == "m") {
var availableMasters = ["ActionScript",
"AppleScript",
"Asp"];
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("Get", "Masters"))",
success: function (data) {
availableMasters = data.list;
},
error: function () {
alert('No Master Available.');
}
});
$("#SearchTitle").autocomplete({
source: availableMasters
});
}
My issue is that the form is binding the availableMasters before the ajax call, so the search textbox always has the static text array that I am adding at the begining with 3 fields. I am getting the correct list of masters in the (data.list) but it never shows up in the textbox.
Is there a way to bind the list once the ajax call get the list of masters?
Thanks for the concerns...
wrap it in a function, say init, and call that function on the success of your ajax call.
function initSearch(){
$("#SearchTitle").autocomplete({
source: availableMasters
});
}
if ($('input[name=SearchType]:checked').val() == "m") {
var availableMasters = ["ActionScript",
"AppleScript",
"Asp"];
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("Get", "Masters"))",
success: function (data) {
availableMasters = data.list;
initSearch();
},
error: function () {
alert('No Master Available.');
}
});
}

Categories

Resources