How to dynamically add the content in jsp page using javascript? - 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.

Related

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>

I can't use '\n" in javascript, I don't know why it isn't work

As I know, writing a new line is "\n", so I tried many times but it wasn't working. This is my source code and screen shot of result
var ary3 = new Array('seven','eight', 'nine');
for (var i =0; i<ary3.length ; i++){
document.getElementById('demo3').innerHTML += i+"'\nth element\n[enter image description here][1] : " + ary3[i]+"\n";
}
<h1>Show me the array object's entry</h1>
<div id = 'demo3'></div>
<br>
Whitespace is generically collapsed to at most a single space in HTML. Example
<div>a
b c</div>
Will appear as just a b c
You have a few options
Use pre
<pre>a
b</pre>
Will appear as
a
b
Use white-space: pre; CSS on your div
<div style="white-space: pre;">a
b</div>
Will break line breaks
Insert <br/> for `\n' as in
var someString = "a\nb\nc";
someElement.innerHTML = someString.replace(/\n/g, "<br/>");
As for your specific example of looping you also have the option to insert separate elements
function insertDivWithText(parent, text) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(text));
parent.appendChild(div);
}
var demo3 = document.querySelector("#demo3");
var ary3 = ['seven','eight', 'nine'];
for (var i = 0; i < ary3.length ; ++i) {
var div = document.createElement("div");
insertDivWithText(demo3, i + "th element");
insertDivWithText(demo3, "[enter image description here][1] : " + ary3[i]);
}
<h1>Show me the array object's entry</h1>
<div id = 'demo3'></div>
<br>
Also note that using .innerHTML with user data is likely going to expose you to scripting vulnerabilities. Consider using document.createTextNode or element.textContent or element.innerText
The problem is that the newline from JS will be rendered as plain space. HTML is responsible for new line showing, but HTML will not pay attention to simple new line in text. You can check your HTML using developer's tools. You will see that JS made new lines:
derveloper tools
To make new line work, you should add <br /> tag
var ary3 = new Array('seven','eight', 'nine');
for (var i =0; i<ary3.length ; i++){
document.getElementById('demo3').innerHTML += i+"'<br/>\nth element<br/>\n[enter image description here][1] : " + ary3[i]+"<br/>\n";
}
<h1>Show me the array object's entry</h1>
<div id = 'demo3'></div>
<br>
You are writing HTML, DOM, so you have to use <br> tag, not newline.
If you are trying to create a HTML new line, use <br>.
Html code for new line is <br>.
As in:
document.getElementById('demo3').innerHTML += i+"'nth element<br>[enter image description
Your output is html. In html, use the <br /> tag to break the line.

Why do I get a type error when trying to access the value of an element stored in a variable?

I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.

Is it possible to use a for loop in <select> in html? and how?

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/

InnerHTML doesn't work in FF?

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.

Categories