I have an array.js file and an index.html.
My array.js file looks like this:
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
My index.html file looks like this:
<html>
<head>
<script type="text/javascript" src="array.js"></script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
<script>
go();
</script>
</body>
</html>
When I click the Display JS Array button on the HTML page, nothing happens.
I want the array elements to be displayed after I click the button.
It should look like:
Red
Blue
Green
You can change the function by taking the parent element of li elements as parameter.
function go(element){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
var ul = document.createElement("ul");
for (var i=0; i < array.length; i++) {
var li = document.createElement("li");
li.innerHtml = array[i];
ul.appendChild(li);
}
body.insertAfter(ul, element);
}
<input type="button" onclick="go(this)" value="Display JS Array"/>
replace this document.write("<li>" + array[i] + "<br />"); with document.write("<li>" + array[i] + "</li>");
and in your HTML file, remove
<script>
go();
</script>
because already you calling go(); function on onclick. and in your array, array[2] will give undefined.
try this its working for me :
<html>
<head>
<script type="text/javascript">
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[2] = "Green";
li = document.getElementById("list");
li_arr = "";
for (var i=0; i < array.length; i++){
li_arr += "<li>" + array[i] + "</li>";
}
li.innerHTML = li_arr;
}
</script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
<ul id="list"></ul>
</body>
</html>
Your code is quite ok. And working fine. Yes you can use external JS or internal JS .
By using External JS: -
Test.html
<html>
<head>
<script type="text/javascript" src="arrayy.js"></script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
</body>
</html>
arrayy.js
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
These above codes are running in Mozilla Firefox ,IE 8 and some other browser.
By Using Internal JS: -
<html>
<head>
<script>
function go(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
</script>
</head>
<body>
<input type="button" onclick="go()" value="Display JS Array"/>
</body>
</html>
It works just fine for me.
But as shreedhar said:
You need to delete
<script>
go();
</script>
this otherwise it will be displayed before you pressed the button.
An since array[2] is undefined you need to filter that one from your array.
Suppose if you are using jquery dom ready function then make the modification on arrayy.js like this.
$(document).ready(function() {
this.go = function(){
var array = new Array();
array[0] = "Red";
array[1] = "Blue";
array[3] = "Green";
for (var i=0; i < array.length; i++){
document.write("<li>" + array[i] + "<br />");
}
}
}
Related
I've got an array in Javascript that I want to print to screen which is: (my function for ro[j] is simplified in this example, but that doesn't matter)
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
$('.result2').html(ro[j]);
}
</script>
But this doesn't work as I think it keeps replacing the div with each loop rather than adding to the div. Is there a good way to implement this? I thought you could try something like this:
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
if(j==0){
$('.result2').html(ro[j]);
}else{
var res = $('.result2').val();
$('.result2').html(res + ro[j]);
}
}
</script>
but this doesn't work since you can't seem to call the result of the script midway through the script? Or I just made a mistake, I'm not sure. Any help would be great!
edit: forgot a semicolon
A list element (ul or ol) should be used for lists as it's more semantically correct:
<ul id="result2"></ul>
Using es6 syntax you can append elements to that list like this:
const ro = [...Array(49).keys()]; // Just setting up a sample array
for (r of ro) {
let li = document.createElement('li');
li.innerHTML = r;
document.getElementById('result2').appendChild(li);
}
This will place the numbers vertically in the screen.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="result2"></div>
<script type='text/javascript'>
var ro = [];
for (var j = 0; j <= 49; j++) {
ro.push(j);
$('.result2').append(ro[j] + '<br />');
}
</script>
</body>
</html>
This question already has answers here:
Why can't I call a function named clear from an onclick attribute?
(3 answers)
Closed 6 years ago.
I have the following html code to clear web storage data after click the button "Clear storage".
The explorer (chrome and firefox) just never trigger the function clear after click the button of clear storage.
The code is:
<html>
<head>
<script>
function clear() {
console.log();
localStorage.clear();
refreshContents();
alert("all cache data cleared!");
}
function refreshContents() {
var str = "";
alert("in refresh");
for (var i = 0, len = localStorage.length; i < len; i++) {
var k = localStorage.key(i);
var v = localStorage.getItem(k);
str += "'" + k + "' = '" + v + "'<br />";
}
alert("after for loop");
key.value = "";
value.value = "";
content.innerHTML = str;
}
</script>
</head>
<body>
<div class="content"> <!-- end .content -->
<p>This is the logout page.</p>
<p>All temporary data will be erased after logout.
<p> </p>
<input type="button" onclick="clear();" value="Clear Storage" />
Contents of Local Storage:<br />
<span id="content"></span>
</body>
</html>
Can someone help please.
Thanks in advance!
Changing the function name did the trick. Just change your function name from clear to anything say clearABC and it will work.
function clearABC()
{
}
The reason for this in this post: is clear a reserved word in javascript
Hope this helps,
Cheers
Happy coding !!
<script type="text/javascript">
function clear() {
console.log();
localStorage.clear();
refreshContents();
alert("all cache data cleared!");
}
function refreshContents() {
var str = "";
alert("in refresh");
for (var i = 0, len = localStorage.length; i < len; i++) {
var k = localStorage.key(i);
var v = localStorage.getItem(k);
str += "'" + k + "' = '" + v + "'<br />";
}
alert("after for loop");
key.value = "";
value.value = "";
content.innerHTML = str;
}
</script>
Update Script tag
I think this one help you
I want to display the content in my div but the code won't work. Please show me how to do it.
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for (i = 0; i < 11; i++) {
var disp = "the number is " + i;
console.log(disp);
}
disp = document.getElementById("display").innerHTML;
</script>
</body>
</html>
How can I get the loop to display my variable in my selected div? Which part of my code is wrong? please help.
Tehre are multiple problems
<p id="display"></p>
<script>
var i;
//initialize the value
var disp = '';
for (i = 0; i < 11; i++) {
//concatenate the value of disp so that new value will be added to the previous content other wise the values will be overwritten
disp += "the number is " + i;
console.log(disp);
}
//assign value of disp to the elemet innerHTML
document.getElementById("display").innerHTML = disp;
</script>
Set the innerHTML inside the for loop.
for (var i = 0; i < 11; i++) {
var disp = "the number is " + i;
document.getElementById("display").innerHTML = disp;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
IF you want to display all the content at once
var disp = ''; // Assign empty string
for (var i = 0; i < 11; i++) {
disp += " the number is " + i; // Concat message
}
document.getElementById("display").innerHTML = disp; // Add into html
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Because you never write anything to your HTML page. You just display it in your console. And later you assign the HTML content of the #display element to the variable disp, which doesn't make any sense:
disp = document.getElementById("display").innerHTML;
This is how it will work
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
// This just writes to the javascript console
console.log(disp);
// This writes in the #display element on your page
document.getElementById("display").innerHTML += disp + '<br>';
}
</script>
</body>
</html>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
console.log(disp);
}
document.getElementById("display").innerHTML = disp;
Something like this should be fine
function createDivs(){
var pContainer = document.getElementById("display");
var i;
for(i = 0; i < 11; i++){
var message = "the number is " + i;
console.log(message);
var element = document.createElement("div");
element.innerHTML = message;
pContainer.appendChild(element);
}
disp = document.getElementById("display").innerHTML;
};
createDivs();
I have a Google Apps Script web app that contains an HTML form with a couple of drop-down lists. When the user submits their choices, a function looks them up in a Google spreadsheet and returns corresponding values in an array. This array could have any length, and I am having trouble getting it to display as an HTML list without having a set list length.
I have this GAS script:
function doGet() {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function discern(formObject) {
var stage = formObject.stage;
var service = formObject.service;
var ss = SpreadsheetApp.openById(ID);
var dataSheet = ss.getSheetByName('Sheet1');
var dataRange = dataSheet.getDataRange();
var data = dataRange.getValues();
var array = [];
for(var i = 0; i < data.length; i++) {
if(data[i][1].indexOf(stage) > -1) {
if(data[i][2].indexOf(service) > -1) {
array.push(data[i][0]);
}
}
}
return array;
}
And this HTML:
<script>
function printList(array) {
var div = document.getElementById('results');
var list = HtmlService.createHtmlOutput('<ul>');
for (var i = 0; i < array.length; i++) {
list.append('<li>' + array[i] + '</li>');
}
list.append('</ul>');
}
</script>
<form id="myForm">
<h3>Farming Stage</h3><br>
Select your farming stage.<br>
<select name="stage">
<option etc etc etc
</select><br>
<h3>Services</h3><br>
Select the service for which you are looking<br>
<select name="service">
<option value= etc etc etc</option>
</select><br>
<br><input type="button" value="Discern"
onclick="google.script.run
.withSuccessHandler(printList)
.discern(this.parentNode)"/>
</form>
<ul id="results"></ul>
(I've replaced some sections with "etc" to save space. The form itself is not the issue.)
Anyway, right now the app returns nothing. Earlier I had the printList function as:
function printList(array) {
var div = document.getElementById('output');
div.innerHTML =
'<ul><li>' + array[0] +
'</li><li>' + array[1] +
'</li><li>' + array[2] +
'</li><li>' + array[3] +
'</li><li>' + array[4] +
'</li></ul>';
}
This version worked, but it was limited to 5 list slots, and the unused slots showed up as "undefined," which was annoying.
Does anyone have any suggestions? Was I close with the 'for' loop in my printList function? Is there another simple way to go about this? I would really appreciate any help or feedback.
Thanks,
Bill
You get the div results do you mean to append the list to the html?
<script>
function printList(array) {
var div = document.getElementById('results');
var list = HtmlService.createHtmlOutput('<ul>');
for (var i = 0; i < array.length; i++) {
list.append('<li>' + array[i] + '</li>');
}
list.append('</ul>');
// ?
div.innerHTML = list.getContent();
}
</script>
edit Also I think you need to getContents of the html Object.
You could not use the HTMLService. Personally I never got it to work the way I wanted it to when I used it. (a couple years ago).
Why not use your loop and just append the string to the div like this.
<script>
function printList(array) {
var div = document.getElementById('results');
var list = '<ul>');
for (var i = 0; i < array.length; i++) {
list += '<li>' + array[i] + '</li>';
}
list += '</ul>';
div.innerHTML = list;
}
</script>
For whatever reason, it worked when I did it this way:
...<br><input type="button" value="Discern"
onclick="google.script.run
.withSuccessHandler(showThings)
.discern(this.parentNode)"/>
</form>
<p>List of services:</p>
<ul id="things">
<li>Waiting...</li>
</ul>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function showThings(array) {
var list = $('#things');
list.empty();
for (var i = 0; i < array.length; i++) {
list.append('<li>' + array[i] + '</li>');
}
}
</script>
I want save textarea lines in js array.
this code works but if we have empty line in textarea, array elements values set undefined after empty line!
DEMO: http://jsfiddle.net/pYTjR/3/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function check(){
var lines = $('#links').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
var links = texts;
var str = links[i];
alert(i+"- "+str);
}
}
</script>
</head>
<body>
<textarea id="links" name="upload" cols=80 rows=10>
www.example.com/book111.pdf
www.example.com/book222.pdf
www.example.com/book333.pdf
www.example.com/book444.pdf
www.example.com/book555.pdf
</textarea>
<input type="submit" id="getsize" name="getsize" value="textarea to array" onclick= "check()" />
</body>
</html>
DEMO: http://jsfiddle.net/pYTjR/3/
I think it is functioning as you are expecting except not alerting correctly. Try this:
http://jsfiddle.net/pYTjR/7/
function check(){
var lines = $('#links').val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
for (var i=0; i < texts.length; i++) {
alert(i+"- "+texts[i]);
}
}