Display elemens of 2 arrays in <li> - javascript

And thanks in advance for looking into this, I am trying to show elements of 2 arrays in html (li) tags. This should be the format echoed out:
array1; array2
c201;100
c202;0
c450;320
......
The elements that will be pushed into the array are coming from input fields. I have created the following code and I get to see the correct format but when I copy and paste the values above, it loses the format and instead of having two columns, it pastes elements of array2 just below the elements of array1:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
var accounts_code_comma = accounts_code_str.split(' ');
var accounts_code_comma = accounts_code_comma.join(';<br>');
array_accounts.push(accounts_code_comma);
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
var iz_credits_comma = iz_credits_comma.join('<br> ');
array_credits.push(iz_credits_comma);
showAccounts();
showCredits();
}
</script>
</head>
<body>
<h1>Accounts and IZ credits</h1>
<div id="form">
<form>
<label>Insertar Accounts codes</label>
<input type="text" name="accounts" id="accounts" />
<label>Insertar Iz credits</label>
<input type="text" name="credits" id="credits" />
<input type ="button" onclick="spara()" value="Process data" />
</form>
</div>
<div id="codes" style="float:left">
<script>
function showAccounts(){
for (var x=0;x<array_accounts.length;x++){
document.write('<div style="float:left;">'+array_accounts[x]+';</div>');
}
}
</script>
</div>
<div id="credits" style="float:left">
<script>
function showCredits(){
for (var i=0;i<array_credits.length;i++){
document.write('<div style="float:left;">'+array_credits[i]+'<br></div>');
}
}
</script>
</div>
</body>
</html>
Many thanks in advance for your help!

Hope this helps!
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
array_accounts = accounts_code_str.split(' ');
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
array_credits=iz_credits_comma;
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
showAccounts();
}
function showAccounts(){
var ol = document.createElement("OL");
for (var x=0;x<array_accounts.length;x++){
var li = document.createElement("LI");
var textnode = document.createTextNode(array_accounts[x]+';'+array_credits[x]);
li.appendChild(textnode);
ol.appendChild(li)
}
document.getElementById("codes").appendChild(ol);
}
</script>
Modify the two javascript functions and that should do the trick! Thanks.

Related

Added text strings do not show in unordered list

I'm trying to code a small application that lets you dynamically add text strings in an unordered list, but the problem is the strings I pass as input do not show up after clicking the "Invia/Send" button. I have tried with a few solutions from other questions, but none of them worked. Any ideas?
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button id="add" onclick="addParagraph(paragraphArray)">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(paragraphArray){
var text = document.getElementById("insertParagraph").value;
var radio = document.getElementById("insertType");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.getElementById("beforeParagraph");
var selectedBeforeParagraph = sel.options[sel.selectedIndex].value;
for(i = 0; i < radio.length; i++){
if(radio[i].checked){
selectedInsertType = radio[i].value;
}
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
There were a few issues:
A common problem people run into with the button tag is by default, it has a type of 'submit' which will submit the form. There are a few ways to disable this, my preferred method is to set the type as button.
Another issue is you don't have any content in the select box, which was causing an error trying to get the value of a select box with no options that can be selected.
I updated your radios, to use querySelectorAll and look for :checked that way you don't need to create an if statement.
I also removed the paragraphArray from addParagraph() since it is a global variable.
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button type="button" id="add" onclick="addParagraph()">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(){
var text = document.getElementById("insertParagraph").value;
var radio = document.querySelectorAll("#insertType:checked");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.querySelector("#beforeParagraph");
var selectedBeforeParagraph = (sel.selectedIndex > -1) ? sel.options[sel.selectedIndex].value : "";
for(i = 0; i < radio.length; i++){
selectedInsertType = radio[i].value;
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>

Functions or loop are not working

So having problems with both methods. Method (this.howMuch) is supposed to calculate the distance given car went (based on speed and time inputs). Method (this.printAll) is supposed to print all information about objects that are in the array. The only error i see is that "carConstruct.howMuch is not a function at HTMLButtonElement". Same error for the second method if i delete the first one.
All help appreciated. Code below:
var vardas = document.getElementById("name");
var laikas = document.getElementById("time");
var greitis = document.getElementById("speed");
var driver = document.getElementById("driver");
var addCar = document.getElementById("addCar");
var race = document.getElementById("race");
var box = document.getElementById("box");
var cars = [];
function carConstruct(name, time, speed, driver, distance){
this.name = name;
this.time = time;
this.speed = speed;
this.driver = driver;
this.distance = 0;
this.howMuch = function(){
for(var i=0; i<cars[i]["time"]; i++){
this.distance = this.distance + (cars[i]["speed"] * cars[i]["time"]);
}
}
this.printAll = function(){
for(var i=0; i<cars.length; i++){
console.log(cars[i]["name"]);
console.log(cars[i]["speed"]);
console.log(cars[i]["driver"]);
console.log(cars[i]["distance"]);
}
}
}
addCar.addEventListener("click", function(){
var carNew = new carConstruct(vardas.value, laikas.value, greitis.value, driver.value);
cars.push(carNew);
vardas.value = "";
greitis.value = "";
driver.value = "";
});
race.addEventListener("click", function(){
carConstruct.howMuch();
carConstruct.printAll();
});
<!doctype html>
<html>
<head>
<title>J21ND</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="J21ND.css">
</head>
<body>
<div class="fields">
<h1>Car Race</h1>
<input id="name" type="text" placeholder="Input car name">
<input id="time" type="number" placeholder="Input car time">
<input id="speed" type="number" placeholder="Input car speed">
<input id="driver" type="text" placeholder="Input driver level, select: Rookie or Pro">
</div>
<div class="buttons">
<button id="addCar">Add Car</button>
<button id="race">Start Race</button>
</div>
<div id="box">
</div>
<script src="J21ND.js"></script>
</body>
</html>
You could do it by simply adding a global flag. Here is the customized code.
// Above code will remain same in js and HTML code will remain same as well
var flag =0;
addCar.addEventListener("click", function(){
var carNew = new carConstruct(vardas.value, laikas.value, greitis.value, driver.value);
cars.push(carNew);
flag=1;
vardas.value = "";
greitis.value = "";
driver.value = "";
});
race.addEventListener("click", function(){
if(flag!=0){
var addedCar = cars.pop()
addedCar.howMuch();
addedCar.printAll();
flag =0;
}else{
alert('Please Add Car First');
flag =0;
}
});

javascript Uncaught TypeError: .indexOf is not a function

This is the javascript code:
/**
* Created by Alejandro on 25/02/2016.
*/
var aantalKoppels = 2;
function setup(){
var btnToevoegen = document.getElementById("btnToevoegen");
btnToevoegen.addEventListener("click", koppelToevoegen);
var btnReplace = document.getElementById("btnReplace");
btnReplace.addEventListener("click", update);
}
function koppelToevoegen() {
var parameterDataKoppel = document.createElement("div");
var labelParameter = document.createElement("label");
labelParameter.innerHTML = "Parameter:";
labelParameter.setAttribute("for", "parameter" + aantalKoppels);
var parameter = document.createElement("input");
parameter.id = "parameter" + aantalKoppels;
parameter.setAttribute("type", "text");
var labelData = document.createElement("label");
labelData.innerHTML = "Data:";
labelData.setAttribute("for", "data" + aantalKoppels);
var data = document.createElement("input");
data.id = "data" + aantalKoppels;
data.setAttribute("type", "text");
parameterDataKoppel.appendChild(labelParameter);
parameterDataKoppel.appendChild(parameter);
parameterDataKoppel.appendChild(labelData);
parameterDataKoppel.appendChild(data);
var parameterDataKoppels = document.getElementById("parameterDataKoppels");
parameterDataKoppels.appendChild(parameterDataKoppel);
aantalKoppels++;
}
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
var template = document.getElementById("template");
vervangAlles(template, parameterDataKoppels);
}
function vervangAlles(template, parameterDataKoppels) {
for(var i = 0; i < parameterDataKoppels.length; i++) {
var result = vervang(template, parameterDataKoppels[i][0], parameterDataKoppels[i][1]);
template = result;
}
var output = document.getElementById("txtOutput");
output.innerHTML = template;
return template;
}
function vervang(template, parameter, data) {
var result = template.substring(0, template.indexOf(parameter)) + data;
var i = template.indexOf(parameter) + parameter.length;
while(template.indexOf(parameter, i) !== -1) {
var indexVolgende = template.indexOf(parameter, i);
result += (template.substring(i, indexVolgende)) + data;
i = indexVolgende + parameter.length;
}
result += template.substring(i, template.length);
return result;
}
window.addEventListener("load",setup,false);
This code should take a template (String), parameters (String word out of text) and data (String) as input to then replace al the parameters in the text by the String data. I do get an error which I can't figure out at the first line in the last function:
Uncaught TypeError: template.indexOf is not a functionvervang # ReplaceFunction.js:61vervangAlles # ReplaceFunction.js:52update # ReplaceFunction.js:47
this is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" charset="utf-8" src="../scripts/ReplaceFunction.js"></script>
<title>ReplaceFunction</title>
</head>
<body>
<div>
<label for="template">Template:</label>
<input id="template" type="text" />
</div>
<div id="parameterDataKoppels">
<div>
<label for="parameter1">Parameter:</label>
<input id="parameter1" type="text" />
<label for="data1">Data:</label>
<input id="data1" type="text" />
</div>
</div>
<input id="btnToevoegen" type="button" value="Koppel toevoegen" />
<input id="btnReplace" type="button" value="Replace" />
<p id="txtOutput">geen output</p>
</body>
</html>
I hope somebody knows why I get this error.
It seems like your 'update' should be
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
//var template = document.getElementById("template");
var template = document.getElementById("template").value;
vervangAlles(template, parameterDataKoppels);
}

Push value to array onclick and loop to add array values. Javascript

So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example

an unordered list from Array items using innerHTML in Javascript

I am trying to add a bulleted list to the page after the user enters 'exit' into a prompt; the list should not include the term 'exit'. I was able to get the list in full using document.write but this included the 'exit' and got rid of my page formatting. I am pretty sure I need to use innerHTML, but when I do this all I get is the page without any of the array items. Any help is greatly appreciated.
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script>
function askMe() {
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit'){
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
var MyList = getElementById('results');
MyList.innerHTML = "<li>"+list+"</li>";
}
}
</script>
</head>
<body onload="askMe()">
<ul>
<div id="results">
</div>
</ul>
<br/>
<br/>
</body>
you have to use document.getElementById() and also generate a string inside the loop and use inner html after the loop so that the previous li's dont get over written.
update the code portions like
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
and in html , remove the div inside ul and giv id to ul
<ul id="results">
</ul>
and here is the full code becomes:
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script type="text/javascript">
function askMe()
{
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit')
{
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++)
{
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
}
</script>
</head>
<body onload="askMe()">
<ul id="results">
</ul>
<br/>
<br/>
</body>
</html>
You should use MyList.innerHTML += "<li>"+list+"</li>"; (notice the use of += instead of =)
Also, change your <ul> HTML to be:
...
<ul id="results">
</ul>
...

Categories

Resources