adding options to select on focus IE9 - javascript

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

Related

jQuery to Javascript adding required attribute

So I have the following jQuery code that I've built out that checks whether a on change event has been triggered on #rtk5 and then either removes or adds the 'required' attribute.
Works perfectly in jQuery:
// Make checkbox textboxes not required unless checked
$(document).ready(function() {
$('#rtk5').change(function() {
if ($('.rtk5ReqField').attr('required')) {
$('.rtk5ReqField').removeAttr('required');
}
else {
$('.rtk5ReqField').attr('required','required');
}
});
});
I would like to convert it to JavaScript with a function call, but I can't seem to figure out how to properly do it.
Error:
TypeError: rtk5req.getAttribute is not a function
Here is my attempt:
var rtk5req = document.getElementsByClassName('rtk5ReqField');
function rtk5Required() {
rtk5req.addEventListener('change', (e) => {
if (rtk5req.getAttribute('required')) {
rtk5req.removeAttribute('required');
} else {
rtk5req.getAttribute('required', 'required');
}
});
}
rtk5req.addEventListener('change', rtk5Required());
document.addEventListener('DOMContentLoaded', rtk5Required);
rtk5Required();
Updated code: Removed the repetitive change call
var rtk5req = document.getElementsByClassName('rtk5ReqField');
function rtk5Required() {
if (rtk5req.getAttribute('required')) {
rtk5req.removeAttribute('required');
} else {
rtk5req.getAttribute('required', 'required');
}
}
rtk5req.addEventListener('change', rtk5Required());
document.addEventListener('DOMContentLoaded', rtk5Required);
rtk5Required();
Updated code #2:
Thanks all for all the hard work, there's one small issue that I'm still experiencing and had to make some tweaking - When I uncheck the checkbox, it doesn't remove the required tag placed on rtk5Declaration from which it did in the jQuery.
var rtk5_selection = document.getElementById('rtk5');
document.addEventListener('DOMContentLoaded', () => {
rtk5_selection.addEventListener('change', () => {
if (rtk5_selection.getAttribute('required')) {
document.getElementById('rtk5Declaration').removeAttribute('required');
} else {
document.getElementById('rtk5Declaration').setAttribute('required', 'required');
}
});
});
Thanks so much all!
Since you only have one element you should be using its ID instead of its class, and avoiding the complication caused by document.getElementsByClassName returning a pseudo-array of elements instead of a single element.
NB: use setAttribute to change an attribute's value, or better yet (as shown in the code below) use the direct boolean property that mirrors the element's attribute.
document.addEventListener('DOMContentLoaded', () => {
const rtk_sel = document.getElementById('rtk5');
const rtk_dec = document.getElementById('rtk5Declaration');
rtk_sel.addEventListener('change', () => {
rtk_dec.required = !rtk_sel.checked;
});
});
Thanks all for the contribution, below is the working version which I have tweaked:
var rtk5_selection = document.getElementById('rtk5');
var rtk5declaration = document.getElementById('rtk5Declaration');
function rtd3Declaration() {
if (!rtk5_selection.checked) {
rtd3declaration.removeAttribute('required');
} else {
rtd3declaration.setAttribute('required', 'required');
}
}
rtk5_selection.addEventListener('change', rtd3Declaration);
document.addEventListener('DOMContentLoaded', rtd3Declaration);
rtd3Declaration();

How to detect DOM modification event

I have been trying to get listen to DOM change event for a several hours, however still cannot get it working.
I need to detect events that are showed in Chrome Debug Tools as changes displayed as pink color.
Here is what I've tried
function listenForDomModified(node, listener) {
node.addEventListener("DOMSubtreeModified", listener, false);
var iframes = node.getElementsByTagName("iframe");
for (var i = 0, len = iframes.length, doc; i < len; ++i) {
// Catch and ignore errors caused by iframes from other domains
try {
doc = iframes[i].contentDocument || iframes[i].contentWindow.document;
doc.addEventListener("DOMSubtreeModified", listener, false);
} catch (ex) {}
}
}
var findElements = function () {
elements.iframeBlock = $(SELECTOR.IFRAME_BLOCK);
};
var onIframeChange = function (e) {
console.log("CHANGE !!!");
alert("DOM CHANGES");
};
var setListeners = function () {
listenForDomModified(elements.iframeBlock[0],onIframeChange);
elements.iframeBlock.bind('DOMSubtreeModified', function(e) {
if (e.target.innerHTML.length > 0) {
alert("ON CHANGE");
}
alert("ON CHANGE");
});
//elements.iframeBlock.change(onIframeChange);
};
Please note, I tried these methods separately.
But still cannot get my function called. However Chrome displays these changes.
I would be grateful for any help.
Thanks
Have you tried
$(document).on('change', function () { /*code*/ });
Try this jQuery approach:
$("iframe").contents().find('body').on("change", function() {
alert("DOM CHANGES");
});
not tested...

javascript dependant drop down not working in IE 8

I have searched through here to find a javascript drop down that changes based on another drop down and the code I have works in Chrome. However, it doesn't work in IE 8.0.6 and I was wondering if anyone could highlight the part that isn't working, or suggest another workaround (JQuery, CSS etc).
When I load this in IE, the second drop down is completely blank. The first drop down has a variation of the arrays, when a user selects one of those, they are then presented with the options in the array. So if I select iAffordability, i will be presented with the three values in the array.
Here is the code I am using
iAffordability = new Array("Unable to Get Mortgage", "Cant Afford to Move", "Price");
iDisintruction = new Array("Branch Disinstructed");
iCourtOrder = new Array("Court Order");
iLackofComms = new Array("Marketing", "Viewings", "Offers");
iLackofOffers = new Array("Not Happy with Amount", "Not Happy with Quality");
populateSelect();
$(function () {
$('#WD').click(function () {
populateSelect();
});
});
function populateSelect() {
WD = $('#WD').val();
$('#Sub').html();
if (WD == 'iAffordability') {
$('#Sub').empty();
iAffordability.forEach(function (t) {
$('#Sub').append('<option>' + t + '</option>');
});
}
if (WD == 'iDisintruction') {
$('#Sub').empty();
iDisintruction.forEach(function (t) {
$('#Sub').append('<option>' + t + '</option>');
});
}
if (WD == 'iLackofComms') {
$('#Sub').empty();
iLackofComms.forEach(function (t) {
$('#Sub').append('<option>' + t + '</option>');
});
}
if (WD == 'iLackofOffers') {
$('#Sub').empty();
iLackofOffers.forEach(function (t) {
$('#Sub').append('<option>' + t + '</option>');
});
}
}
JS Fiddle
UPDATE:
The code worked, I just had to add in:
if (!window.console) console = {log: function() {}};
to my existing JS.
I'm going to suggest a refactoring and DRYing of your code:
var lists = {
iAffordability: ["Unable to Get Mortgage", "Cant Afford to Move", "Price"],
iDisintruction: ["Branch Disinstructed"],
iCourtOrder: ["Court Order"],
iLackofComms: ["Marketing", "Viewings", "Offers"],
iLackofOffers: ["Not Happy with Amount", "Not Happy with Quality"]
};
$(function () {
populateSelect();
$('#WD').change(function () {
populateSelect();
});
});
function populateSelect() {
var WD = $('#WD').val(), $sub = $('#Sub');
$sub.empty();
$.each(lists[WD] || ["Error"], function(_, t) {
$sub.append('<option>' + t + '</option>');
});
}
This should work even in older versions of IE because it uses the jQuery $.each function instead of Array.prototype.forEach - as RobG pointed out, this function was only added in IE9 (ah, if only IE forced itself to update like Chrome does...) and it should be much easier to expand in future.

Test existence of object properties in IE

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

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