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>
Related
var inputItem = document.getElementById("inputItem");
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
var deleteButton = document.createElement("button");
deleteButton.innerText = "delete";
deleteButton.addEventListener("click", function() {
//console.log("Delete");
//var ul=document.getElementById("list");
var listItem = list.children;
for (var i=0; i < listItem.length; i++) {
while(listItem[i] && listItem[i].children[0].checked) {
ul.removeChild(listItem[i]);
}
}
});
var checkBox = document.createElement("input");
checkBox.type = 'checkbox';
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
label.appendChild(checkBox);
label.appendChild(labelText);
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem">
<input type="submit">
</form>
<ul id="list">
</ul>
</body>
</html>
So first of all, there are a few little mistakes in the code:
var list = document.getElementById(list); - You're using the list as the parameter, not a string.
while(listItem[i] && listItem[i].children[0].checked) { - Not sure why you're using while here instead of if.
ul.removeChild(listItem[i]); - ul is commented a few lines above.
Besides these, the delete does not work because of the following line:
if(listItem[i] && listItem[i].children[0].checked) {
If you analyze the DOM, the list item contains a <label></label> that contains the input, which means children[0] is not what you expect it to be.
Therefore, fixing the issues mentioned above and replacing the check in the delete callback function with
if(listItem[i] && listItem[i].getElementsByTagName('input')[0].checked) {
list.removeChild(listItem[i]);
}
should be your fix.
So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.
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.
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;
}
});
I have a simple HTML unordered list and a JavaScript function that adds items at position [0], and another that deletes items at [0] as well, but what can I add to the delete function (strictly basic JavaScript please even if it's longer) so it deletes the last added item? Thank you in advance:
HTML:
<html>
<body>
<h1> Shopping List </h1>
<button onclick="adding()"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button onclick="remove()"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Javascript:
function adding() {
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
newEl.appendChild(newText);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
}
function remove() {
var removeEl = document.getElementsByTagName("li")[0];
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
}
function adding() {
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
newEl.appendChild(newText);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
}
function remove() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
}
<html>
<h1> Shopping List </h1>
<button onclick="adding()"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button onclick="remove()"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
Besides, try not to use attribute event handlers like onclick="adding()". A much better practice is to attach them programmatically, for clean separation of concerns:
<button id="add">Add</button>
and then
document.getElementById('add').addEventListener('click', adding);
Purely speaking this answers the question as it only removes the last added item then won't remove anything else
window.lastadded = false;
function adding() {
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
newEl.id = Date.parse(new Date());
var newText = document.createTextNode(input);
window.lastadded = newEl.id;
newEl.appendChild(newText);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
}
function remove() {
lastElement = document.getElementById(window.lastadded);
lastElement.parentNode.removeChild(lastElement);
}