Cannot append in IE, works in Firefox and Chrome - javascript

I think IE hates me. Everything I do in other browsers works, but IE 11, no! It is failing. I'm guessing it's me and not the browser.
I have a <select> list on my web page, and I'm trying to bind the <option> dynamically.
So far, it works great in Firefox and Chrome, but not in IE. There is no error in the IE Development tools (F12) so I'm lost as to why it refuses to work.
JSFIDDLE
HTML
<select id="MyList">
</select>
Javascript
$(function() {
var myItems=[];
myItems.push({"All":"Hello"});
myItems.push({"One":"And More"});
myItems.push({"Two":"Lots More"});
for (i = 0; i< myItems.length;i++) {
for (item in myItems[i]) {
var x = myItems[i][item]; //for my testing
var y = myItems[item]; //for my testing
$("#MyList").append("<option>" + item + "</option>");
}
}
});
If you try the fiddle in FF or Chrome, all good. The select list populates with All, One and Two.
Short of a gift or even some form of sacrifice to the IE elves, what do I need to do to make IE happy with me?

This is bizarre. When I run that fiddle in the IE I have handy (IE9), I get an "access denied" error and jQuery isn't loaded. If I change the fiddle to use 1.11.0 rather than 1.10.1, I don't get that error and the script runs.
There are a couple of issues with the code, primarily undeclared variables (your code was falling prey to The Horror of Implicit Globals); here's an updated fiddle with:
Variable declarations
Using jQuery 1.11.0
Using the "no wrap - body" option rather than "onload", since you're using the ready event
Here's the code:
$(function() {
var myItems=[];
myItems.push({"All":"Hello"});
myItems.push({"One":"And More"});
myItems.push({"Two":"Lots More"});
var i, item;
for (i = 0; i< myItems.length;i++) {
for (item in myItems[i]) {
var x = myItems[i][item];
var y = myItems[item];
$("#MyList").append("<option>" + item + "</option>");
}
}
});
Separately, though, to be compatible with a wider range of browsers, you might want to use the Option constructor and the add method of the options list rather than appending a DOM element; some older browsers prefer it. That looks like this: Fiddle
// Before the loop...
var options = $("#MyList")[0].options;
// ...in the loop
options.add(new Option(item));

JSFIDDLE
var sel = $("#MyList");
sel.empty();
for (var i = 0; i< myItems.length;i++) {
for (var item in myItems[i]) {
var x = myItems[i][item];
var y = item;
console.log(x);
console.log(y);
sel.append('<option value="' + x + '">' + y + '</option>');
}
}
As already mentioned by # T.J.Crowder in IE 10 jquery1.10.1 is not working and updating the jquery version to later it started to work;

Try this
$(function() {
var myItems=[];
myItems.push({"All":"Hello"});
myItems.push({"One":"And More"});
myItems.push({"Two":"Lots More"});
for (i = 0; i< myItems.length;i++) {
for (item in myItems[i]) {
var x = myItems[i][item];
$('#MyList')
.append($("<option></option>")
.attr("value",x)
.text(item));
}
}
});

Related

How to Loop on an array in Javascript?

When I run this code it reads only index 0 what is wrong?
Javascript:
function openTabs()
{
var data = document.getElementById('excelData').value;
var rows = data.split("\n");
for(var i = 0; i < rows.length; i++)
{
window.open('http://www.google.com/search?q=' + rows[i]);
}
}
HTML:
<textarea id = "excelData" name="excel_data" style="width:300px;height:580px;"></textarea><br>
<input type="button" onclick="openTabs()" value="Open Tabs"/>
There is nothing wrong with neither the code before the loop nor the loop itself. I suspect the browser you are using is blocking you from opening som many windows.
You can verify this by changing the line to something else, for example console.log(rows[i]); and see if that outputs more than the first element in the index.
This depends on the browser. If you are using Chrome, it will block opening multiple windows at the same instant. To allow this, in the address bar, click Pop-ups blocked and select "Always show pop-ups from [site]"
You can try by setting a the name property of the window.open method. ALong with that you may need to allow pop up from the browser.
Here is snippet to add name property to window.open
function openTabs() {
var data = document.getElementById('excelData').value;
var rows = data.split("\n");
for (var i = 0; i < rows.length; i++) {
// second parameter is the name
window.open('http://www.google.com/search?q=' + rows[i],'newWindow'+i);
}
}
DEMO
Allow popup from the browser option

Javascript only working in Chrome browser not in Firefox

So I have a table and I have to populate a modal using the data from the Table I have written following code
Javascript
var tableHeaders = JSON.parse('["name","phone","email","message"]');
console.log(tableHeaders) ;
$('.openUpdateform').on('click', function() {
$('#callApi').hide();
$('#updateData').show();
tr = $(this).parent().parent().parent().parent();
console.log(tr.children());
for (var i = 1; i < tr.children().length - 1; i++) {
j = i - 1;
$('#' + tableHeaders[j]).val(tr.children()[i].outerText);
}
$('#data_row_id').val($(this).data('row_id'));
$('#createWF').modal();
})
JSFIDDLE
SO the above code works perfectly on Chrome but not in Mozilla Firefox any suggestions appreciated .
Not Working
Means from the Action DropDown if you select the Edit Data option it will open a popup and that popup gets filled in Chrome but not Firefox.
Thanks
the problem is that Firefox doesn't support Node.outerText. Use Node.innerText instead and you'll be all right.
You must use "innerText" instead of "outerText".
https://developer.mozilla.org/es/docs/Web/API/HTMLElement/outerText

Loop does not work as intended

http://codepen.io/abdulahhamzic/pen/aNexYj
I'm trying to get this loop to correctly print out ten results on the screen, but it seems like there is something wrong with my loop and I can't figure out what that is. On Mozilla, I only get the first result displayed on the screen and it seems like the loop is stuck after the first iteration, and on Chrome I get the ten results, but it looks like the loop is still running afterwards since I can't really do any styling on the newly created elements, plus I still get that loading icon on the page. Can anyone help me in fixing this loop? Here's the code:
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=aa&limit=10&callback=?";
$(document).ready(function(){
$.getJSON(url, function(json){
for (var i = 0; i < json[1].length; i++){
document.write("<div><span class='header' style='color:red'>" + json[1][i] + "</span><br>" + json[2][i] + "</div><br>")
}
})
})
The document.write() function is dangerous and has different behaviour over different browsers. Better not use it. You can have something like the below working code:
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=aa&limit=10&callback=?";
$(document).ready(function(){
$.getJSON(url, function(json){
for (var i = 0; i < json[1].length; i++){
$("body").append("<div><span class='header' style='color:red'>" + json[1][i] + "</span><br>" + json[2][i] + "</div><br>")
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Can I use javascript timer in a mobile browser

I am using IE in a mobile browser. I add a javascript function to a button that when the User clicks it says 'hello'.
This works.
I then add a timer.
On a desktop browser it works.
it does not work on my mobile browser.
This is my code. (note I Had just tried placing an alert('hi'); in the swapImages() and that did not work either.
var div = document.getElementById('divImage');
var imgCached = document.getElementById('imgCached');
document.execCommand("BackgroundImageCache", false, true);
function OnImgLoaded() {
img1.src = imgCached.src;
}
var interval = 30;
var _timer;
var _index = 0;
function test() {
_timer = setInterval('swapImages()', interval);
}
function swapImages() {
imgCached.onload = OnImgLoaded();
imgCached.src = 'my server url~/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
}
UPDATE!!
I had been runningit on Chrome desktop and not IE. I am mow testing it in IE desktop. I get the same erro so now I can debug.
The error is this line:
img1.src = imgCached.src;
It tells me:
Unable to get property 'src' of undefined or null reference
I have changed the code to:
var imgLive = document.getElementById('imgLive'); (I have renamed the img control)
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
I get the same error.
I look in Source and the control is correctly named..
Thanks
i'm not sure that the following line is valid in your mobile phone:
imgCached.src = 'http://127.0.0.1/Cloud/test/' ...
the timer executes successfully, but the image doesn't get the proper src since the device doesn't run a web server on it (unless you configured one).
and to answer your topic question, yes- you can use javascript timers in mobile browsers just like desktop browsers.
hope that helped.
First of all: Do you ever call the test function, that starts the timer?
Second: Maybe it's really document.execCommand("BackgroundImageCache", false, true), that fails - it may not be enabled in the mobile version of IE that you are using. You can check if it's enabled using the queryCommandEnabled function, see more here: http://msdn.microsoft.com/en-us/library/ie/ms536676(v=vs.85).aspx

Jquery attr('src') undefined in IE 8 (works in FF)

This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The snippet we have is used twice.
The old code
<script type="text/javascript">
jQuery(document).ready(function() {
//...
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
// Write contents
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
//...
});
//...
// Change entry
jQuery('.blogentry').each(function(){
entryindex = jQuery(this).attr('rel');
if (entry == entryindex)
{
// The following works fine (so 'children' works fine):
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
// This does not work - only in IE 8, works in Firefox
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
//alert: 'undefined'
alert(jQuery(this).children('.Image_center').attr('src'));
//...
}
}
//...
});
</script>
The new code
Please see my own posted answer for the new code.
UPDATE:
This does not work if called inside of the click event!!!
jQuery('.Image_left').each(function(){
alert(jQuery(this).attr('src'));
});
SOLUTION TO GET THE IMAGE DATA:
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//... inside the eventhandler (entryindex = 'rel' of blogentry):
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
This works because it is not called inside the event handler and the sources are saved beforehand
BUT! I still cannot write the data, which is my aim:
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
UPDATE!!!
This is just crazy, I tried to write the data via usual javascript. This also works in FF, but no in IE8. Here really is some serious problem witt the attribute src:
document.getElementById('bild_left').src = imgleft;
document.getElementById('bild_center').src = imgcenter;
document.getElementById('bild_right').src = imgright;
alert(document.getElementById('bild_left').src);
This works in FF, but not in IE8, the attribute src remains undefined after writing! This seems to be not a jQuery problem at all!
children looks for immediate child elements only where as find looks for all the elements within it until its last child element down the dom tree. If you are saying find is working that means the element you are looking is not its immediate children.
Try to alert this jQuery(this).children('#Image_center').length see what you get.
FYI. Even when any element is not found jQuery will return an emtpy object it will never be null. So alert an emtpy object will always give you [object Object]. You should alwasy check for the length property of the jQuery object.
Try this
alert(jQuery(this).find('#Image_center').length);//To check whether element is found or not.
Bing Bang Boom,
imgright = jQuery(".Image_right",this).attr('src');
And why don't you easily use one working?
alert(jQuery(this).children('#Image_center').attr('src'));
change children to find
alert(jQuery(this).find('#Image_center').attr('src'));
It is probably the easiest solution, and when it work, why wouldn't you use it?
the problem is not in the attr('src') but in something else. The following snippet works in IE8:
<img id="xxx" src="yrdd">
<script type="text/javascript">
alert($('#xxx').attr('src'));
</script>
But if you for example change the the text/javascript to application/javascript - this code will work in FF but will not work in IE8
This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The new code
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
entryindex = jQuery(this).attr('rel');
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
// Write contents
jQuery('#entryimages').html('');
jQuery('#entryimages').html('<img class="rotate" width="132" height="138" id="bild_left" src="'+imgleft+'" /><img class="rotateright" width="154" height="162" id="bild_center" src="'+imgcenter+'" /><img class="rotate" width="132" height="138" id="bild_right" src="'+imgright+'" />');
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
});
So I am just not using .attr('src') in the event handler....
Try to make a delay:
jQuery(document).ready(function() {
setTimeout(function () {
jQuery('.blogentry').each(function(){
// your code...
});
}, 100); // if doesn't work, try to set a higher value
});
UPDATE
Hope, this code will work.
$('.blogentry img').each(function(){
alert( $(this).attr('src') );
});
UPDATE
I'm not sure, but maybe IE can't read classes with uppercase first letter...
Try to change ".Image_center" to ".image_center"
UPDATE
Check your code again. You definitely have some error. Try this jsfiddle in IE8, attr('src') is showed correctly. http://jsfiddle.net/qzFU8/
$(document).ready(function () {
$("#imgReload").click(function () {
$('#<%=imgCaptcha.ClientID %>').removeAttr("src");
$('#<%=imgCaptcha.ClientID %>').attr("src", "Captcha.ashx");
});
});

Categories

Resources