InnerHTML doesn't work in FF? - javascript

i'm pretty new to Javascript and basiclly everything related to web
coding. i have a simple problem using InnerHTML in FF, i hope you can
help me.
i'm using this code, that should generate a simple html input line,
and in IE it works fine (although when i load it i get the "should i
enable activeX msg on top), but in FF it doesn't work at all, i can
see it's on the page thorugh source, but it doesn't show anything...
<div id="mainDiv"></div>
<script type="text/javascript">
var siteBoxes = '<form action=HTMLPage.htm name="myform">';
for (var i = 0; i < arr1.length; i++) {
siteBoxes += '<INPUT TYPE="checkbox" id="box'+i+'"
VALUE="'+arr1[i]+'"/> '+arrNames[i]+'';
}
siteBoxes += '';
document.getElementById("mainDiv").innerHTML=siteBoxes;
i'm sure it's a simple solution, and i tried searching on the web, but
i'm running out of strength for that, i hope any of you kind people
can help me.
thanks in advance!!!
ok, the problem is with the array definition in the head.
i just noticed that in the error console in FF i get a msg that the arr1 is undefined, but it is, i even tried moving it to the body and it doesn't change, still undefined... and it works in IE.
could it be something with the array definition? is it different from IE and FF???
var arr1 = new Array(
"http://www.google.com",
"http://www.yahoo.com",
"http://www.cnet.com",
"http://www.google.ar/search?q="
);
again, it works great in IE, but not in FF

Somethings I noticed at first glance.
<div id="mainDiv"></div>
<script type="text/javascript">
var siteBoxes = '<form action="HTMLPage.htm" name="myform">';//put quotes around page
for (var i = 0; i < arr1.length; i++) {
siteBoxes += '<INPUT TYPE="checkbox" id="box'+i+'" VALUE="'+arr1[i]+'"\/>
'+arrNames[i]+'<br \/><br \/>';
}
siteBoxes += '<\/form>';
document.getElementById("mainDiv").innerHTML=siteBoxes;
arr1 is never declared at least from the code you present to us.

Works in Opera, IE and FF for me.
Try unescaping the output;
document.getElementById("mainDiv").innerHTML = unescape(siteBoxes);

There is something wrong with the ending quotation mark in your script tag. If I delete it and type a new one, the code works.

There must be a problem with the rest of your code because when I change it. It works fine.
<html>
<head>
</head>
<body>
<div id="mainDiv"></div>
<script type="text/javascript">
var arr1 = new Array();
var arrNames = new Array();
arr1[0] = "test";
arrNames[0] = "nameTest";
var siteBoxes = '<form action=HTMLPage.htm name="myform">';
for (var i = 0; i < arr1.length; i++) {
siteBoxes += '<INPUT TYPE="checkbox" id="box'+i+'" VALUE="'+arr1[i]+'"/> '+arrNames[i]+'<br /><br />';
}
siteBoxes += '</form>';
document.getElementById("mainDiv").innerHTML = siteBoxes;
</script>
</body>
</html>

Here's perhaps a cleaner way of implementing this (see comments in code as well):
//You can use the simple way of creating an array, and instead of having two
//arrays that represent the names and urls, just make a single array of JSON
var sitesArray = [
{siteName: "Google",siteUrl:"http://www.google.com"},
{siteName: "Yahoo",siteUrl:"http://www.yahoo.com"},
{siteName: "CNET",siteUrl:"http://www.cnet.com"},
{siteName: "Google Search",siteUrl:"http://www.google.ar/search?q="}
];
//Create an ouput array where you'll compile your html
var outputArray = [];
//Now loop through sitesArray and push the strings onto the ouputArray
for (var i=0,len=arr1.length;i < len;++i) {
outputArray.push("<input type=\"checkbox\" id=\"box",i,"\" ",
"value="\",sitesArray[i].siteUrl,"\" />&nbsp",
sitesArray[i].siteName,"<br /><br />");
}
document.getElementById("mainDiv").innerHTML = outputArray.join("");
The primary reason for suggesting this is that string concatenation can be very slow, especially if you have lots of long strings. It's not as big an issue in Firefox, but it's definitely an issue in IE. So pushing strings onto an array, then joining them at the end will give you better performance.

Related

Creating javascript loop in html

I wanted to make a javascript loop in html like the following:
( if (var i=0; i<10; i++) { ) //<-- JAVASCRIPT
//HTML
( } ) //<-- JAVASCRIPT
I tried using the <% JAVASCRIPT %> but it won't work for me. Does anyone know who to solve this?
Thanks in advance.  
This is not how javascript works. This is something you would do with PHP.
With javascript, you run it seperately from the html. Then, you create an element within your html as a wrapper to put the javascript generated html into. Like so:
HTML
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '<span class="test">Testing out my script!</span>';
wrapper.innerHTML = myHTML
</script>
See a working example here
Sorry I skipped over the for loop by the way. Let me fix it with this update... You could do it like this, you see:
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
for (var i = 0; i < 10; i++) {
myHTML += '<span class="test">Testing out my script! loop #' + (i + 1) + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML
</script>
for loops are control flow and thus cannot be inserted into a static context. Try mapping it, e.g.
`<html>` + data.map(function(a) { return `<div>${a}</div>` }).join('') + `</html>`
<script>
for(var i=0; i<10; i++) {
//Code here
}
</script>
https://www.w3schools.com/js/js_if_else.asp
https://www.w3schools.com/js/js_loop_for.asp
I'd suggest you read a bit before going straight into coding
Either way your script seems deficient and I cant make out what you are trying to do with it.
Check these links if you want to append elements:
https://www.w3schools.com/jquery/html_append.asp
https://www.w3schools.com/jsref/met_node_appendchild.asp

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

How to dynamically add the content in jsp page using javascript?

MyServlet forwards to Mypage.jsp as
request.getRequestDispatcher("/pages_homepage.jsp?value="+count).forward(request, response);
where count is an integer value generated
Below is my JSP code(Mypage.jsp),
<body onload="getPage('<%request.getParameter("value");%>')">
<div id="app"></div>
</body>
Below is my javascript code,
function getPage(match){
var arr = new Array();
var ele = document.getElementById('app');
for(var i=0;i<match;i++){
var newdiv = document.createElement("label");
newdiv.id = arr[i];
newdiv.value="Page";
ele.appendChild(newdiv);
}
}
What I want is that, I want 'Page' to be displayed 'match' number of times. But I'm not being able to do so by the above code. Their might be something wrong with my js code. Can anyone suggest me any corrections?
Thanks in advance.
LIVE DEMO
Taking in consideration that your page has something like:
<body onload="getPage(5)">
function getPage(n) {
var ele = $('#app');
var labels = ""; // An empty string will be populated with labels elements:
for(var i=0; i<n; i++){
labels += '<label id="'+ i +'"> Page </label>'
}
ele.append( labels ); // append only once outside the loop!
}
The result will be:
<label id="0"></label>
<label id="1"></label>
<label id="2"></label>
<label id="3"></label>
<label id="4"></label>
If you want to start from 1 instead of 0 use:
labels += '<label id="'+ (i+1) +'"> Page </label>'
Note: ID starting with (/ containing only) a number - is only valid in HTML5
Your Code is working and i have tested it
Since you don't have any content in the label tag hence it is not visible in browser
Secondly a small error
in 6th line of js code
newdiv.id = arr[i];
arr[i] is not given any value hence change it with
newdiv.id = i;
enjoy your code
Thanks everyone for their help but I think I got the answer,
Instead of
<body onload="getPage('<%request.getParameter("value");%>')">
I wrote,
<body onload="getPage('<%=Integer.parseInt(request.getParameter("value"))%>')">
But thanks everyone again for their useful pointers.

Javascript - How do you set the value of a button with an element from an array?

<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);

Google Caja appendChild not updating form.elements in Firefox

I'm using a Google Apps Script Web App and HtmlService to serve the content and I'm trying to dynamically add input elements to a form with appendChild. It works in Chrome 24 and IE 10, but Firefox 19.0.2 doesn't update the elements listing for the form.
So, it displays correctly on the webpage, but in Firefox, any input elements added with appendChild to the form aren't part of the form.elements collection. It's worth noting this issue only appears when the HTML is sanitized with Caja, if I use the same code in jsfiddle it works fine.
The issue can be seen here, which is just the following code:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function print(form)
{
var str = "";
for(var v = 0; v < form.length; v++)
{
str += "<br>" + form[v].nodeName + "." + form[v].id + ": ";
if(form[v].elements != undefined)
for(var w = 0; w < form[v].elements.length; w++)
{
str += form[v].elements[w].name + ", ";
}
}
return str;
}
function submitForm()
{
document.getElementById("nameLookupHelp").innerHTML = (print(document.forms)) + "<br>Total Elements:" + document.forms[0].elements.length;
return;
}
function onLoad()
{
var name = document.getElementById("nameForm");
var t = document.createElement("input");
t.name = "TestInput";
//t.id = "TestInput";
name.appendChild(t);
}
</script>
</head>
<body onload="onLoad()">
<form name="nameForm" id="nameForm">
<input name="nameLookup" id="nameLookup">
<input type="button" id="bntNameForm" onclick="submitForm(this)" value="Lookup">
<div class="" id="nameLookupHelp">Please enter your name.</div>
</form>
</body>
</html>
From what I've found on the subject, Firefox doesn't like invalid HTML; however, from what I can tell, the HTML output is perfectly valid. More over, since it works on jsfiddle, I assume the issue has to be with the way Caja is interacting with my HTML and Firefox.
Also, one last thing, if I inspect the form element in Firefox and double click on the form tag in the markup panel, then click off (cancel editing), Firefox then detects all of the elements and everything works fine. What Firefox displays as the HTML doesn't change though.
Thank you in advanced for your help.
Congratulations, you found a bug; a form's .elements never updates after the first time it is accessed. I have fixed it in Caja r5321.

Categories