Test existence of object properties in IE - javascript

Using jQuery with IE doesn't work for me.
I have ajax response:
{"update":{"WaterLever":null},"missing":["WaterBallast"]}
Firing different functions upon response:
$.post(...
...
function(data) {
markMissing(data['missing']);
fldUpdate(data['update']);
}
all is working in chrome/FF but only fldUpdate in IE.
IE doesn't find the elements in the object, tried .indexOf, (val in data) etc...
function markMissing(data) {
//loop all fields in form..
$('[id^=cont]').each(function() {
var s = this.id;
//discard prefix 'cont_' in id.
var fld = s.substring(5);
if(fld in data) { //this doesn't work
//if(data.indexOf(fld)) { //this neither.
$(this).addClass('missing');
} else {
$(this).removeClass('missing');
}
});
}
Thanks for any input

Related

html() function with variables

I'm attempting to inject some html code with variables in it into a JQM UL Listview. The problem I am running into is it seems the variables are throwing off the code because when I remove them, it injects the HTML perfectly.
Here is the snippet:
$(document).on("pageinit", "#vendorMessages", function() {
var listView = "";
pubnub.subscribe(
{
channelGroup: getChannelGroup()
},
function (status, response) {
alert("test");
console.log(status, response);
}
);
pubnub.channelGroups.listChannels(
{
channelGroup: getChannelGroup()
},
function (status, response) {
response.channels.forEach( function (channel) {
var channelFormatted = String(channel).split("_");
var channelMember = channelFormatted[1];
var temp = "<li onClick='loadChannel("+channel+")'>"+channelMember+"</li>";
var temp = String(temp);
listView = listView.concat(temp);
})
alert(listView);
}
)
var elem = $("#channels");
elem.html(elem.text(listView));
$("#channels").listview("refresh");
})
The alert(listView) returns the correct string format but the code still will not get added to the <ul>. I've tried a few suggested things, even switching back to javascript innerHTML but no avail. Any thoughts?
Change
elem.html(elem.text(listView));
to
elem.html(listView);
elem.text cannot handle html..

Running a form handled by ajax in a loaded ajax page?

Using tutorials found i'm currently loading new pages with this:
$("a.nav-link").click(function (e) {
// cancel the default behaviour
e.preventDefault();
// get the address of the link
var href = $(this).attr('href');
// getting the desired element for working with it later
var $wrap = $('#userright');
$wrap
// removing old data
.html('')
// slide it up
.hide()
// load the remote page
.load(href + ' #userright', function () {
// now slide it down
$wrap.fadeIn();
});
});
This loads the selected pages perfectly, however the pages have forms that themselves use ajax to send the following:
var frm = $('#profileform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data)
}
});
However this is not sending the form as it did before the page itself was called to the parent page via ajax. Am I missing something? Can you not use an ajax call in a page already called by ajax?
I also have other issues, for example I disable the submit button unless there are any changes to the form, using:
var button = $('#profile-submit');
var orig = [];
$.fn.getType = function () {
return this[0].tagName == "INPUT" ? $(this[0]).attr("type").toLowerCase() : this[0].tagName.toLowerCase();
}
$("#profileform :input").each(function () {
var type = $(this).getType();
var tmp = {
'type': type,
'value': $(this).val()
};
if (type == 'radio') {
tmp.checked = $(this).is(':checked');
}
orig[$(this).attr('id')] = tmp;
});
$('#profileform').bind('change keyup', function () {
var disable = true;
$("#profileform :input").each(function () {
var type = $(this).getType();
var id = $(this).attr('id');
if (type == 'text' || type == 'select') {
disable = (orig[id].value == $(this).val());
} else if (type == 'radio') {
disable = (orig[id].checked == $(this).is(':checked'));
}
if (!disable) {
return false; // break out of loop
}
});
button.prop('disabled', disable);});
However this also doesn't work when pulled to the parent page. Any help much appreciated! I'm really new to ajax so please point out any obvious mistakes! Many thanks in advance.
UPDATE
Just an update to what i've found. I've got one form working by using:
$(document).on('mouseenter', '#profile', function() {
However the following:
$(document).on('mouseenter', '#cancelimage', function() {
$('#cancelimage').onclick=function() {
function closePreview() {
ias.cancelSelection();
ias.update();
popup('popUpDiv');
$('#imgForm')[0].reset();
} }; });
Is not working. I understand now that I need to make it realise code was there, so I wrapped all of my code in a mouseover for the new div, but certain parts still don't work, so I gave a mouseover to the cancel button on my image form, but when clicked it doesn't do any of the things it's supposed to.
For anyone else who comes across it, if you've got a function name assigned to it, it should pass fine regardless. I was trying to update it, and there was no need. Doh!
function closePreview() {
ias.cancelSelection();
ias.update();
popup('popUpDiv');
$('#imgForm')[0].reset();
};
Works just fine.

submit during beforeunload, maybe who knows radically another method solution

Reviewed many similar questions on stackoverflow.com (also on other resources), but found no answers. So I simplified and generalized questions. It seems like the obvious solution:
$(document).ready(function() {
var a = 3;
var b = 5;
// no message when pressed submit button
$('form').submit(function() {
$(window).off('beforeunload');
});
// confirm of the need to save
$(window).on('beforeunload', function(e) {
if (a != b)
if (confirm('You changed data. Save?')) {
$('form').submit();
// alert('Your data is saved. (With alert submit() work only in FireFox!?)');
}
});
});
But not submit work. If you use the alert(), it works only in FireFox. I would like to correct (possibly without delay) cross-browser solution. Maybe who knows radically another method solution.
P.S. On some originality beforeunload described here in the first part: https://stackoverflow.com/a/6065085/1356425, but this is not the solution obvious functional.
Chrome and Firefox blocking submits after the onbeforeunload-event. You have to use
$(window).on('beforeunload', function(e) {
if (a != b)
return 'You\'ve changed the data. Leave page anyway?';
}
});
I used synchronous AJAX (JAX) request and run handler for events onUnload or onBeforeUnload once for the respective browser. This solution has a single and almost cross-browser behavior.
Example (on jsfiddle):
$(document).ready(function() {
var form = $('form');
var textareas = $('textarea');
function array_compare(a_0, a_1) {
if(a_0.length != a_1.length)
return false;
for(i = 0; i < a_0.length; i++)
if(a_0[i] != a_1[i])
return false;
return true;
}
var flag = false; // flag to control the execution of the unloadHandler() once
var a_open = []; // array with data before unload
$('textarea').each(function(index) {
a_open.push($(this).val());
});
function unloadHandler() {
if (flag)
return;
var a_close = []; // array with data during unload
$('textarea').each(function(index) {
a_close.push($(this).val());
});
if (!array_compare(a_open, a_close)) {
if (confirm('You changed the data, but not saved them. Save?')) {
$.ajax({
type: 'POST',
url: '/echo/json/',
async: false,
data: form.serialize()/* {
json: JSON.stringify({
text: 'My test text.'
}),
delay: 3
} */,
success: function(data) {
if (data) {
console.log(data);
alert('All data is saved!');
}
}
});
}
}
flag = true;
}
// For FireFox, Chrome
$(window).on('beforeunload', function () {
unloadHandler();
});
// For Opera, Konqueror
$(window).unload(function() {
unloadHandler();
});
// Without message when pressed submit button
$('form').submit(function() {
$(window).off('beforeunload');
$(window).off('unload');
});
});
Best way to submit data on unload is to store it in localstorage and send it next time when any other page under same origin is requested.
function sendBeacon(data) {
data?dataArr.push(data):'';
for (var i = 0, len = dataArr.length; i < len; i++) {
$.getScript(dataArr[i], (function (index) {
dataArr.splice(index, 1) //Updata dataArray on data submission
}(i)))
}
}
$(window).on('beforeunload', function () {
localStorage.setItem('dataArr', JSON.stringify(dataArr));
})
var dataArr = JSON.parse(localStorage.getItem('dataArr'));
if (!dataArr) {
dataArr = []; // Create Empty Array
} else {
sendBeacon(dataArr); //Submit stored data
}

adding options to select on focus IE9

I'm trying to lazy load options into a select with jquery. This code works in all browsers I've tested except IE9. (IE7, IE8, FF, Chrome all work)
function LazyLoadOptionsIntoSelect($select, options) {
//get current option
var selectedOptionVal = $select.val();
var selectedOptionDisplay = $select.find("option:selected").text();
//repopulate options
if (selectedOptionDisplay === "--Select a File--"
|| selectedOptionDisplay === "----------") {
$select.html("");
$("<option>").val("").text("--Select a File--")
.appendTo($select);
}
else {
$select.html($("option:selected", $select));
$("<option>").val("").text("----------")
.appendTo($select);
}
$.each(options, function () {
var item = this;
$("<option>").attr("name", function () { return item.display; })
.val(item.value)
.text(item.display)
.appendTo($select);
});
//select previous val
$select.val(selectedOptionVal);
}
$(document).on("focus", ".html-select", function () {
LazyLoadOptionsIntoSelect($(this), HtmlOptions);
});
$(document).on("focus", ".txt-select", function () {
LazyLoadOptionsIntoSelect($(this), TxtOptions);
});
$(document).on("focus", ".xml-select", function () {
LazyLoadOptionsIntoSelect($(this), XmlOptions);
});
I've been trying to solve this for hours but nothing is working.. any solutions or do I need to write a different way to load options in IE9?
options is an array of objects containing value, and display.
This works in simpler use cases, but this apparently is too much for Microsoft to handle. <_<
After hours of fiddling, I tried changing the css to see if redrawing the element worked. It did.
$(document).on("focus", ".html-select", function () {
LazyLoadOptionsIntoSelect($(this), HtmlOptions);
if ( $("body").hasClass("ie9") )
{
$(this).width($(this).width());
}
});

Javascript code error at Internet Explorer

My web + Jquery plugins is working well on Firefox, Chrome, Safari (win & Osx) & Android also. But it sucks with Windows + Internet Explorer because it does not load some js. I am going crazy because it works in all scenarios but IE.
IE shows me 3 errors warnings. My question is. Must IE compile perfect all these 3 errors before showing well the page? For example I have a real time search using jquery, but it does not work on IE due it shows me an error with that code.
Please could you help me validate this "valid" code? Thank you all in advance
$(function() {
// find all the input elements with title attributes
$('input[title!=""]').hint();
}
);
(function ($) {
$.fn.hint = function (blurClass) {
if (!blurClass) {
blurClass = 'blur'; }
return this.each(function () {
// get jQuery version of 'this'
var $input = $(this),
// capture the rest of the variable to allow for reuse
title = $input.attr('title'),
$form = $(this.form),
$win = $(window); function remove() {
if ($input.val() === title && $input.hasClass(blurClass)) {
$input.val('').removeClass(blurClass); }
}
// only apply logic if the element has the attribute
if (title) {
// on blur, set value to title attr if text is blank
$input.blur(function () {
if (this.value === '') {
$input.val(title).addClass(blurClass); }
}
).focus(remove).blur(); // now change all inputs to title
// clear the pre-defined text when form is submitted
$form.submit(remove); $win.unload(remove); // handles Firefox's autocomplete
}
}
); }; }
)(jQuery);
var options, a;
jQuery(function() {
var onAutocompleteSelect = function(value,
data) {
window.open('ITEM.PRO?&token=#AVP'navegante'&S=' + value.substring(value.length - 4)); }
options = {
serviceUrl : 'JQUERY-#AVP$_SETLANG$.pro',
onSelect : onAutocompleteSelect, }; a = $('#query').autocomplete(options); }
);
Next code in your example maybe have some errors:
original code:
var options, a;
jQuery(function() {
var onAutocompleteSelect = function(value,
data) {
window.open('ITEM.PRO?&token=#AVP'navegante'&S=' + value.substring(value.length - 4)); }
options = {
serviceUrl : 'JQUERY-#AVP$_SETLANG$.pro',
onSelect : onAutocompleteSelect, }; a = $('#query').autocomplete(options); }
);
changed code:
var options, a;
jQuery(function() {
var onAutocompleteSelect = function(value, data) {
// in next line added plus signs before and after *navegante*
window.open('ITEM.PRO?&token=#AVP'+navegante+'&S='+value.substring(value.length-4));
}; // semicolon added
options = {
serviceUrl : 'JQUERY-#AVP$_SETLANG$.pro',
// in next line removed comma. I think: it generate error in IE
onSelect : onAutocompleteSelect //,
};
a = $('#query').autocomplete(options);
});
I tried several j queries in my website .. Most common problem i faced was this and there was nothing wrong with j query but i had to download the latest >jquery.js file and rename it also with the jquery.js ..

Categories

Resources