I have a code that will copy the file names and add them to the textarea. Everything works but when you add more files, the first ones are deleted. How to fix it?
updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
output.innerHTML = '';
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '\n' + input.files.item(i).name + '';
}
output.innerHTML += ' \n';
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Display file name in page after selecting file in file input</title>
</head>
<form>
<input type="file" name="file" id="file" multiple
onchange="javascript:updateList()" />
<br/>Selected files:
<textarea id="fileList"></textarea>
<script src="js/index.js"></script>
</body>
</html>
FIDDLE: https://jsfiddle.net/yhw8zfue/
You are setting your textarea value to empty string.
You can fix by removing the line:
output.innerHTML = '';
When you add more files the function will run again and updste your filelist. but in your code you reset the list of files here:
output.innerHTML = '';
so instead you want to have whats currently in there. replace it with that:
updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
output.innerHTML = output.value;
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '\n' + input.files.item(i).name + '';
}
output.innerHTML += ' \n';
}
Related
I can't figure out why this code won't display the user entered information. I need to have user enter information from the html form, add this info to the arrays, and then display the info (actually, need to do more than this, but can't get past this point). I need the entered information to display on the page. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
</html>
I tried to run the code. I got an error like
test.html:23 Uncaught ReferenceError: fName is not defined
You can solve this by moving the variable declaration inside the function.
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Function to add user info to arrays
function insert() {
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
var display = document.getElementById("display");
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
The reason for this is the element is no there when the initial declaration is happening.
Move the script below the body
The main issue is that the Javascript is loaded before the HTML. As a result, when the Javascript attempts to find the element with the element "firstName", it fails to find it because it hasn't been loaded yet.
To fix this, you should move the script tag below the body tag so that the HTML is loaded before it is accessed by the Javascript.
As an added bonus, it improves page load time as the browser doesn't have to wait for the JavaScript to load before rendering the HTML
Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "Last Name: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</html>
I'm trying to get and display the image and information of a clicked pokemon from pokemon API
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="pokedex2.js"></script>
<link rel="stylesheet" href="pokedex2.css">
<title>Pokedex v 2.0</title>
</head>
<body>
<div id="all">
<div id="pokemon">
</div>
<div id="chosen">
</div>
</div>
</body>
</html>
JavaScript
$(document).ready(function(){
for(i = 1; i <=151; i ++){
$("#pokemon").append("<img id=pokepic" + i + "
src='http://pokeapi.co/media/img/" + i +
".png'>");
}
var clicked = false;
$("img").click(function(){
clicked = true;
console.log(this);
if(clicked){
$.get("http://pokeapi.co/api/v1/pokemon/" + i +"/", function(data){
var str = "";
str += "<h4>Types</h4>";
str += "<ul>";
var str2 = "";
str2 += "<h4>height</h4>";
str2 += "<ul>";
var str3 = "";
str3 += "<h4>weight</h4>";
str3 += "<ul>";
for(i = 0; i < data.types.length; i ++){
str += "<li>" + data.types[i].name + "</li>";
}
str2 += "<li>" + data.height + "</li>";
str3 += "<li>" + data.weight + "</li>";
str += "</ul>"
str2 += "</ul>"
str3 += "</ul>"
$("#chosen").html(str + str2 + str3); }, "json");
}
else{
clicked = false;
}
})
});
At the moment, the only information being brought up are for the first 3 pokemon in the list, not for the pokemon that was clicked. I need to find the information associated with the clicked pokemon, like a pokedex.
I included console.log to show that whichever image is clicked, the picture, and pokepic ID number associated with that image appear in the console. Instead what I need is for the image and stats associated with each image to appear in the div labeled chosen
Your click event uses the i variable defined in your for loop. Since the function inside the click is always called after the loop is done, i is always 152. You need to read the current pokemon from your click event:
$('img').on('click', function(e){
var pokemonId = e.target.id.split('pokepic')[1];
$.get("http://pokeapi.co/api/v1/pokemon/" + pokemonId +"/", function(data){
...
});
});
i have csv file with the content :
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
I create Javascript/HTML code to pick up that file and display the content
<html>
<head>
<title>show csv</title>
</head>
<body>
<input type="file" id="fileinput" multiple />
<div id="result"></div>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
var res = document.getElementById("result");
res.innerHTML = "Got the file<br>"
+"name: " + f.name + "<br>"
+"type: " + f.type + "<br>"
+"size: " + f.size + " bytes</br>"
+ "starts with: " + contents;
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',readMultipleFiles, false);
</script>
</body>
</html>
and the output is like :
output
question : How can i convert the content or the data to array and showing as html table ?
thanks for any help.
You can convert csv data into array and then into html table. I have added \n into your new line. Please add the \n to your code when there is a new line.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
I found Kapila Perera's answer to be very useful. However, the last element of each row was being cropped due to the slice(0,-1) use. Building on Perera's answer, in the example below I've used slice() instead.
I've also separated out the first row lines[0] as a header row and loop from 1 instead (which won't always be the case that csv contains headers but is explicitly called out in the example).
Finally, I've added the tbody tags when the output gets wrapped but this probably isn't required.
<script type="text/javascript"charset="utf-8">
var div = document.getElementById('container');
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"), output = [], i;
/* HEADERS */
output.push("<tr><th>"
+ lines[0].slice().split(",").join("</th><th>")
+ "</th></tr>");
for (i = 1; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice().split(",").join("</td><td>")
+ "</td></tr>");
output = "<table><tbody>"
+ output.join("") + "</tbody></table>";
div.innerHTML = output;
</script>
I am trying to print 6 random numbers after clicking a button. Then every time I click the button again, random numbers should start from new line however I do not know how. I tried everything and nothing works. I appreciate any help.
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
<!DOCTYPE html>
<html>
<head>
<title>Let's ROLL!</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
input, button {display: block;}
</style>
<script>
var number = "";
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
</script>
</head>
<body>
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
</body>
</html>
Not 100% clear on where you wanted the breaks, but in a text area, a line break is \n. If this was in an HTML element, you would use <br />.
var number = "";
function fname() {
for (i = 1; i <= 6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
}
number = number + "\n";
var print = number + "GOOD LUCK!";
document.getElementById("total").value = print;
}
input,
button {
display: block;
}
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
Add "\n".
I am assuming you want to concatenate the new text in the text area, so you should use += instead of =:
document.getElementById("total").value += print + "\n";
You can use arrays and .join() the numbers and lines together by their appropriate delimiters. This only inserts the characters between the elements. \n in a string renders a new line.
var button = document.getElementById('roll');
var total = document.getElementById('total');
var rolls = [];
button.onclick = function() {
var roll = [];
for(var i=0; i<6; ++i) roll.push(Math.floor(Math.random() * 47 + 1));
rolls.push(roll.join('-'));
total.value = rolls.join('\n') + "\nGOOD LUCK!";
}
<button id="roll">ROLL!</button><br>
<textarea id="total" rows="12" cols="50" readonly></textarea>
I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}