setTimeout() doesn't seem to be working in Firefox? - javascript

I have inherited a website! which was designed to work in IE and only IE it seems.. I've now been asked to make the site run in Firefox. I've fixed most of the bugs without any problems but this one has me stumped.
setTimeout(fDelayedFunc, 1000);
This line of Javascript, works fine in IE but in Firefox the function fDelayedFunc never fires. I've removed the setTimeout and the function wrapper and tried running the code as part of the main function. This works without any problems at all.
There is alot of code involved but here's the main but I'm having trouble with. If you'd like to see anymore of the code please let me know.
setTimeout(fDelayedFunc, 0);
//Save the current text box value
var vCurrentTBValue = vJQElement.val();
function fDelayedFunc() {
if (vJQElement.val() == vCurrentTBValue) {
alert("test");
//Get position list box should appear in
var vTop = vJQElement.position().top + 25;
var vLeft = vJQElement.position().left;
//Had to put a special case in for account due to the position co-ords being wrong. This is due to a css error
if (vHiddenFieldToWriteTo == "#ctl00_ContentPlaceHolder1_hfAccountCode") {
vTop = vJQElement.position().top + 58;
vLeft = vJQElement.position().left + 200;
}
else {
vTop = vJQElement.position().top + 25;
vLeft = vJQElement.position().left;
}
//Create div element
var vDivElement = $("<div id='divSearchBox' style='position:absolute; top:" + vTop + ";left:" + vLeft + "; z-index: 40000;'></div>");
//Create list box
var vListBox = $("<select id='lbResults' tabIndex='" + vJQElement.attr("tabIndex") + "' size='4' style='height:400px;'></select>");
//Bind a function to the list box which will select the item via either tab or enter
vListBox.bind("keydown", function() {
//Check if tab or enter has been pressed
if (event.keyCode == 9 || event.keyCode == 13) {
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val());
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
}
//Check if the up arrow has been pressed at the top of the listbox
else if (event.keyCode == 38 && $(vListBox.find(":selected")).val() == $(vListBox.find(":first")).val()) {
//Focus back on the search box
vElement.focus();
}
}).bind("dblclick", function() {
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val());
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
});
//Get search field
var vSearchText = vJQElement.val();
var vDepotID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfDepotID").val();
var vCustomerID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCustomerID").val();
var vCountryID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCountryID").val();
var vConsignee = vJQElement.attr("boolConsignee");
//Set a loading image in place until call completed
vJQElement.css("backgroundImage", "url(images/small-loader.gif)");
vJQElement.css("backgroundRepeat", "no-repeat");
vJQElement.css("backgroundPosition", "right");
//Make AJAX call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewConsignment.asmx/fGetAddressesAndIDs",
data: "{'strSearchText' : '" + vSearchText + "', 'intDepotID' : '" + vDepotID + "', 'intCustomerID' : '" + vCustomerID + "', 'intCountryID' : '" + vCountryID + "', 'boolConsignee' : '" + vConsignee + "'}",
dataType: "json",
success: function fGetAddressesAndIDsResult(GetAddressesAndIDsResult) {
//Make sure there are results
if (GetAddressesAndIDsResult != null && GetAddressesAndIDsResult != "") {
var vNumberOfResults = 0;
var vNumberOfLearntAddresses = 0;
var vLearntAddressUniqueID = "";
//Try to get results (first call will work on Linux and catch will work on Windows)
try {
//Check array exists (if this fails will go to catch)
if (GetAddressesAndIDsResult.d.length > 0) {
//Loop through the results
$.each(GetAddressesAndIDsResult.d, function() {
//Check for results
if (this.length > 0) {
//Evaluate JSON
var vAddress = eval("(" + this + ")");
//Create list item
var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>");
//Find out number of learnt addresses
if (vAddress.uniqueID.indexOf("ConLA") != -1) {
vNumberOfLearntAddresses++;
vLearntAddressUniqueID = vAddress.uniqueID;
}
//Add list item to list box
vListBox.append(vOption);
//Mark result added
vNumberOfResults++;
}
});
}
}
catch (err) {
//Loop through the results
$.each(GetAddressesAndIDsResult, function() {
//Check for results
if (this.length > 0) {
//Evaluate JSON
var vAddress = eval("(" + this + ")");
//Create list item
var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>");
//Find out number of learnt addresses
if (vAddress.uniqueID.indexOf("ConLA") != -1) {
vNumberOfLearntAddresses++;
vLearntAddressUniqueID = vAddress.uniqueID;
}
//Add list item to list box
vListBox.append(vOption);
//Mark result added
vNumberOfResults++;
}
});
}
//Check if only 1 learnt address was found
if (vNumberOfLearntAddresses == 1) {
//Auto select this address
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val(vLearntAddressUniqueID);
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
}
//Add list box to div
vDivElement.append(vListBox);
//Check if any results exist in div
if (vNumberOfResults != 0) {
//Append div to page
$("body").append(vDivElement);
//Auto select first item
vListBox.find(".AddressOption:first").attr("selected", "true");
}
}
//Hide loading image
vJQElement.css("backgroundImage", "none");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//Inform user of error
alert("An error occured, please try again");
//Hide loading image
vJQElement.css("backgroundImage", "none");
}
});
}
}

Try this:
setTimeout(function() { fDelayedFunc(); }, 0);

I took setTimeout(function () {function1();}, 1500) out from the addEventListener("load", () => {code})
it worked for me inside Firefox

try this : setTimeout('fDelayedFunc()', 0);

Related

getJSON does not work on button click but does with hitting enter key

My getJSON request and the rest of my function works fine if the user hits enter after filling out the field however my function does not get past the getJSON request if they click the search button.
I've found some similar post on SO but haven't been able to fix my issue yet. I've tried adding .live before my .click event and also tried adding e.preventDefault in a couple different spots but that hasn't resolved it either.
My HTML looks like this
<input id="zipCode" maxlength="5" type="text"> <button id="zipSearch" onclick="findByZip()">Search</button></p>
My JS looks like this
$(document).ready(function () {
$('#zipSearch').click(findByZip);
$('#zipCode').bind('keydown', function (e) {
if (e.keyCode === 13) { // 13 is enter key
e.preventDefault();
findByZip();
return false;
}
});
}
);
function findByZip() {
console.log('running findByZip');
var zip = $('#zipCode').val();
var stateName = $('#stateName');
stateName.text("Reps for " + zip);
$("#results").empty();
var url='//something.com/api/Reps?Zipcode=' + zip;
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
if (data.length == 0) {
var header = "<h3>No matches found.</h3>"
$('#result').append(header);
}
else {
$.each(data, function (i, item) {
var header = "<h3>Manufacturer's Representative</h3>";
var businessName = $("<h4 id=businessName" + i + "></h4>").text(item.BusinessName);
var contactName = $("<h4 id=contactName" + i + "></h4>").text(item.Contact);
var address = $("<div id=address" + i + "></div>").text(item.Address);
var address2 = $("<div id=address2" + i + "></div>").text(item.City + ", " + item.State + " " + item.Zipcode);
var phone1 = $("<div id=phone1" + i + "></div>").text("PH: " + item.Phone1);
var phone2 = $("<div id=phone2" + i + "></div>").text("PH2: " + item.Phone2);
var fax = $("<div id=fax" + i + "></div>").text("FAX: " + item.Fax);
var email = '<div id=email' + i + '>' + item.Email + '</div>';
var website = '<div id=website' + i + '>' + item.Website + '</div>';
if (item.RegionalRepId == item.Id) {
header = "<h3>Regional Manager</h3>";
}
$("#results").append(header, businessName, contactName, address, address2, phone1, phone2, fax, email, website);
if (businessName[0].textContent == "null") {
$("#businessName" + i).remove();
}
if (contactName[0].textContent == "null") {
$("#contactName" + i).remove();
}
if (address[0].textContent == "null") {
$("#address" + i).remove();
$("#address" + i).remove();
}
if (phone1[0].textContent == "PH:null") {
$("#phone1" + i).remove();
}
if (phone2[0].textContent == "PH2:null") {
$("#phone2" + i).remove();
}
if (fax[0].textContent == "FAX:null") {
$("#fax" + i).remove();
}
if (email.includes("null")) {
$("#email" + i).remove();
}
if (website.includes("null")) {
$("#website" + i).remove();
}
});
}
});
}
expected result is to just pull and display data by different click events and searches to a map. Clicking on a state works, typing in a zipcode and hitting enter works, but typing in a zipcode and clicking search does not work.
If you guys have any suggestions it would be greatly appreciated. Young in my career, mostly have worked in .NET, C#, and Xamarin. Unfortunatly JS and JQuery are a little new to me. Thanks!
My form wasn't preventing a default on form via the submit button. It was only preventing the default on enter. Once I added type="button" inside my <button> tag everything worked fine.

How to set the order of dropdown list items according to their ID numbers in GeoJSON properties

It is my fiddle: http://jsfiddle.net/anton9ov/d8yga33f/
I need to organize an order of items in my selector according to the ID numbers in the GeoJSON file. It is a part of my code where the items appear in the list:
map.on("layeradd", function(e) {
if(!e.layer.options) {
return;
}
if((e.layer.options.id != "markerLayer1") && (e.layer.options.id != "markerLayer2")) {
return;
}
var markers = e.layer.getLayers();
var mySelector = $("#mySelector");
for(var i = 0; i < markers.length; i++) {
mySelector.append("<option value='" + L.stamp(markers[i]) + "'>" + markers[i].feature.properties.name + "</option>");
}
});
Try using Array.prototype.sort():
map.on("layeradd", function(e) {
// ...
var markers = e.layer.getLayers();
// Get the dropdown
var mySelector = $("#mySelector");
markers.sort(function(a,b) {
// get the ids, and parse them as int
var aId = parseInt(a.feature.properties.id,10),
bId = parseInt(b.feature.properties.id,10);
return aId < bId ? -1 : aId > bId ? 1 : 0
}).forEach(function(marker) {
mySelector.append("<option value='"
+ L.stamp(marker) + "'>"
+ marker.feature.properties.id // I added the marker id
+ '. '
+ marker.feature.properties.name
+ "</option>");
})
});
See forked fiddle

How to add auto complete address to dynamically added input fields

I want that user to see an alert whenever he doesn't enter proper Google address (or select from suggestion box) on dynamically added text areas. How can I perform that?
I have tried the following code.
I want that when I add new divs at runtime the auto-complete method should apply on that input field and when the user clicks submit button without selecting any suggested address it should display an alert.
Please help me where am I wrong in my code?
function updateNames() {
var rows = $(".clonedInput");
var index = 0;
rows.each(function () {
var inputFields = $(this).find("input");
inputFields.each(function () {
var currentName = $(this).attr("name");
$(this).removeClass("hasDatepicker");
$(this).removeClass("hasTimepicker");
$(this).attr("name", currentName.replace(/\[(.*?)\]/, '[' + index + ']'));
});
var textareaFields = $(this).find("textarea");
textareaFields.each(function () {
var currName = $(this).attr("name");
$(this).attr("name", currName.replace(/\[(.*?)\]/, '[' + index + ']'));
var places = new google.maps.places.Autocomplete(currName);
var a = places.getPlace();
if (a == null) {
alert('Please Select a valid location');
}
else { }
var currId = $(this).attr("id");
$(this).attr("id", currId.replace(/\[(.*?)\]/, '[' + index + ']'));
});
var numberSpan = $(this).find("span.taskNumber");
numberSpan.html(index + 1);
index++;
});
}

While appending divs, delete older appended divs when there are more than 10

Consider the following JQuery loop. It appends this:
"<div id='1'>" + feedback + "</div>"
1st Question.
I want to increment the id of the appended div after the first one has been appended so that the first appended div's id is 1, the second div's id is 2 and so on.
2nd Question.
When the number of divs reaches 10, I want to delete the first appended div. Which in our case is:
<div id="1">php result</div>
This should keep looping and deleting older divs.
Here's the Jquery ajax loop:
new get_fb();
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "algorithm.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 8000);
}).responseText;
$('#BuzFeed').append("<div id='1'>" + feedback + "</div>");
}
For counting:
var get_fb = (function() {
var counter = 1;
return function(){
var feedback = $.ajax({
...
}).responseText;
$('#BuzFeed').append("<div id='" + counter + "'>" + feedback + "</div>");
}
})();
get_fb();
and for automatic removal, after
var $buzfeed = $('#BuzFeed').append("<div id='" + counter + "'>" + feedback + "</div>");
add
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.first().remove(); }
Additionally, your code uses some not-so-good practices. The re-write, including my additions would be:
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
dataType: "html", // based on chat
url: "algorithm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>");
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.first().remove(); }
setTimeout(get_fb, 8000);
}).fail(function(jqXhr, textStatus, errorThrown) {
var $buzfeedresults = $("<div id='BuzFeedError'></div>");
$buzfeedresults.text('Error: ' + textStatus);
if (typeof console !== 'undefined') {
console.error(jqXhr, textStatus, errorThrown);
}
});
};
})();
get_fb();

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources