Use user form input in JS - javascript

could someone please explain how i get user input from a form to use in JS? ive tried numerous things and the alert just keeps saying {object undefined}? It must be something simple but i cant seem to find the answer anywhere!
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href = "style.css" rel ="stylesheet" type = "text/css">
<script src="script.js" type ="text/javascript" defer ></script>
<title>Tip Calculator</title>
</head>
<body class = "body">
<div class = "form-container">
<h1 class = "heading">Tip Calculator</h1>
<form class = "form" method="GET" action="">
<label for = "bill-amount">How much is the Bill?</label><br>
<input type = "number" placeholder="£0.00" name = "bill-amount" id="bill-amount" data-bill><br>
<label for = "service">How was the Service?</label><br>
<select name = "serivce" id = "service">
<option value = "poor">Poor - 5%</option>
<option value = "good">Good - 10%</option>
<option value = "excellent">Excellent - 20%</option><br>
</select><br>
<label for = "people" name = "people">How many People are spliting the Tip?</label><br>
<input type = "number" name = "people" id = "people"><br>
<input type = "submit" name = "submit" class = "submit" id = "submit">
</form>
<div class = "output">
<p> Tip amount: <span class = "bill-amount">£0</span></p>
<p> Tip amount: <span class = "tip-amount">£0</span></p>
<p> Tip Per Person: <span class = "tip-person-amount">£0</span></p>
</div>
</div>
</body>
</html>
JS
const bill = document.getElementById('bill-amount')
const submit = document.getElementById('submit')
submit.addEventListener('click', function() {
alert(bill)
})

You can access the value of the field by using .value as shown in the code below. The example below pulls the value from the specified selector bill-amount field after the forms is submitted which is presumably after its received input. As a side note, since you're likely going to be doing calculations with this number, remember you have to parse that string into a float. You can do that with .parseFloat.
const submit = document.getElementById('submit');
const bill = document.getElementById('bill-amount');
submit.addEventListener('click', function() {
alert(bill.value) //returns a string to parse use .parseFloat
})

I think you should put the id bill-amount to the input element not the label.
and then use something like:
bill = document.querySelector("#bill-amount").innerText;
this way the value that the user input will be stored in bill

The issue is that bill in your example is a reference to the HTML element with the id bill-amount. It's not a value by itself. To extract the value from the HTML element, you can do the following: bill.value. I have created a working snippet below based upon your sample code.
const bill = document.getElementById('bill-amount')
const submit = document.getElementById('submit')
submit.addEventListener('click', function() {
alert(bill.value)
})
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href = "style.css" rel ="stylesheet" type = "text/css">
<script src="script.js" type ="text/javascript" defer ></script>
<title>Tip Calculator</title>
</head>
<body class = "body">
<div class = "form-container">
<h1 class = "heading">Tip Calculator</h1>
<form class = "form" method="GET" action="">
<label for = "bill-amount">How much is the Bill?</label><br>
<input type = "number" placeholder="£0.00" name = "bill-amount" id="bill-amount" data-bill><br>
<label for = "service">How was the Service?</label><br>
<select name = "serivce" id = "service">
<option value = "poor">Poor - 5%</option>
<option value = "good">Good - 10%</option>
<option value = "excellent">Excellent - 20%</option><br>
</select><br>
<label for = "people" name = "people">How many People are spliting the Tip?</label><br>
<input type = "number" name = "people" id = "people"><br>
<input type = "submit" name = "submit" class = "submit" id = "submit">
</form>
<div class = "output">
<p> Tip amount: <span class = "bill-amount">£0</span></p>
<p> Tip amount: <span class = "tip-amount">£0</span></p>
<p> Tip Per Person: <span class = "tip-person-amount">£0</span></p>
</div>
</div>
</body>
</html>

const bill = document.getElementById('bill-amount')
const submit = document.getElementById('submit')
const form = document.forms[0] // documentGetById, by className or querySelector
form.addEventListener("submit", e => {
e.preventDefault()
const form = e.target;
console.log(form.elements)
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href = "style.css" rel ="stylesheet" type = "text/css">
<script src="script.js" type ="text/javascript" defer ></script>
<title>Tip Calculator</title>
</head>
<body class = "body">
<div class = "form-container">
<h1 class = "heading">Tip Calculator</h1>
<form class = "form" method="GET" action="">
<label for = "bill-amount">How much is the Bill?</label><br>
<input type = "number" placeholder="£0.00" name = "bill-amount" id="bill-amount" data-bill><br>
<label for = "service">How was the Service?</label><br>
<select name = "serivce" id = "service">
<option value = "poor">Poor - 5%</option>
<option value = "good">Good - 10%</option>
<option value = "excellent">Excellent - 20%</option><br>
</select><br>
<label for = "people" name = "people">How many People are spliting the Tip?</label><br>
<input type = "number" name = "people" id = "people"><br>
<input type = "submit" name = "submit" class = "submit" id = "submit">
</form>
<div class = "output">
<p> Tip amount: <span class = "bill-amount">£0</span></p>
<p> Tip amount: <span class = "tip-amount">£0</span></p>
<p> Tip Per Person: <span class = "tip-person-amount">£0</span></p>
</div>
</div>
</body>
</html>

Related

Cant get input from HTML txtbox going to JS w/ API

I am testing API calls from HTML textbox going to JS. How can you get input HTML going to JS and insert it to the URL?
(change var city to textbox from HTML) I need to add the textbox input to the JS query API URL + textbox.textbox1 + API URL
HTML code:
<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">
<title>API</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
crossorigin="anonymous"></script>
<script src = "script.js">
</script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="weather-container">
<img class ="icon">
<p class="weather"> </p>
<p class="temp"></p>
</div>
<form action="/url" method="GET">
<p>Insert City:</p>
<input type ="text" name="city" id="citytext" placeholder="City">
<button type = "submit" id="btn1" name = "submit">Submit</button>
</form>
</body>
Here is the JS
var city = "New York"
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data){
console.log(data)
var icon ="https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp);
var weather = data.weather[0].main;
$('.icon').attr('src', icon);
$('.weather').append(weather);
$('.temp').append(temp);
});
You need to add click event listener on the submit button, also you need to turn its type to button to not reload the page, and then instead of use hardcoded city name, you get it from the input value.
const cityInput = document.getElementById('citytext');
const submitButton = document.getElementById('btn1');
submitButton.addEventListener('click', () => {
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + cityInput.value + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data){
var icon ="https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp);
var weather = data.weather[0].main;
console.log(weather)
$('.icon').attr('src', icon);
$('.weather').append(weather);
$('.temp').append(temp);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="weather-container">
<img class ="icon">
<p class="weather"> </p>
<p class="temp"></p>
</div>
<form>
<p>Insert City:</p>
<input type ="text" name="city" id="citytext" placeholder="City">
<button type = "button" id="btn1" name = "submit">Submit</button>
</form>
</body>

Cannot read properties of null (reading 'addEventListener') when trying to console.log the value of the html input tag when btn click

I'm trying to create a make addEventListener function to a button, when click it should print the value of the input.
but I'm getting an error message:
Cannot read properties of null (reading 'addEventListener')
let plus = document.getElementById('btnPlus');
let minus = document.getElementById('btnMinus');
let multiplay = document.getElementById('btnMultiplay');
let divide = document.getElementById('btnDivide');
let inputOne = document.getElementById('firstNum');
let inputTwo = document.getElementById('secondNum');
// if + button click display in result inputOne + inputTwo
plus.addEventListener('click', function() {
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
console.log(valueOne);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calcultaor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="mainHeader">
<h1> Calculator </h1>
<label for="">Enter First Number</label>
<input type="text" class="firstNum"> <br/>
<label for="">Enter Second Number</label>
<input type="text" class="secondNum"><br/>
<button class="btnPlus">+</button>
<button class="btnMinus">-</button>
<button class="btnMultiplay">*</button>
<button class="btnDivide">/</button>
<h2> The Result Is <span class=span_result /> </h2>
</div>
<script src="app.js"></script>
</body>
</html>
getElementById works only with ID not with classes. Review your HTML
Because this code does not contain an id
<button class="btnPlus">+</button>
If you want get an element by id, the element must contain the id.
Try this
<button id="btnPlus">+</button>
The addEventListener() method attaches an event handler to an element.
You don't have an element with id btnPlus.
Now the below code is running fine.
You have to define the variable as a Number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="mainHeader">
<h1>Calculator</h1>
<label for="">Enter First Number</label>
<input type="text" id="firstNum" /> <br />
<label for="">Enter Second Number</label>
<input type="text" id="secondNum" /><br />
<button id="btnPlus">+</button>
<button id="btnMinus">-</button>
<button id="btnMultiplay">*</button>
<button id="btnDivide">/</button>
<h2>The Result Is <span id="span_result" /></h2>
</div>
<p id="demo">
<script>
let plus = document.getElementById("btnPlus");
let minus = document.getElementById("btnMinus");
let multiplay = document.getElementById("btnMultiplay");
let divide = document.getElementById("btnDivide");
let inputOne = document.getElementById("firstNum");
let inputTwo = document.getElementById("secondNum");
const element = plus;
element.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)+ Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element2 = minus;
element2.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)- Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element3 = multiplay;
element3.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)* Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element4 = divide;
element4.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)/ Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
</script>
</p>
</body>
</html>

change input field value stores in local storage using Javascript

I'm trying to pass an input value from page to the another page..
Using local storage was useful, but when I'm trying to change the value in the second page it doesn't changed, I want to be able to change it..
html code for the first page
<html>
<head>
<title>
Input Form
</title>
<link rel="stylesheet" href="style.css" />
<script>
function handleSubmit () {
const name = document.getElementById('name').value;
const surname = document.getElementById('surname').value;
localStorage.setItem("NAME", name);
localStorage.setItem("SURNAME", surname);
return;
}
</script>
</head>
<body>
<form action="result.html" method="POST">
<input type="text" id="name" name="name" placeholder="Enter name.." />
<input type="text" id="surname" name="surname" placeholder="Enter surname.." />
<input type="submit" onclick="handleSubmit()"/>
</form>
</body>
</html>
html code for second page
<html>
<head>
<title>
Result Page
</title>
<link rel="stylesheet" href="style.css" />
<script>
window.addEventListener('load', () => {
const name = sessionStorage.getItem('NAME');
const surname = sessionStorage.getItem('SURNAME');
document.getElementById('result-name').value = name;
document.getElementById('result-surname').value = surname;
})
</script>
</head>
<body>
<h1>
Result Page
</h1>
<h2>
Name: <input id="result-name" />
</h2>
<h2>
Surname: <input id="result-surname" />
</h2>
</body>
</html>
You are using local storage to set the item. You need to use local storage to get the item. Not session storage.
I am talking about these lines here:
const name = sessionStorage.getItem('NAME');
const surname = sessionStorage.getItem('SURNAME');
I changed it for you. Just copy paste the whole page and you are good to go.
<html>
<head>
<title>
Result Page
</title>
<link rel="stylesheet" href="style.css" />
<script>
window.addEventListener('load', () => {
const name = localStorage.getItem('NAME');
const surname = localStorage.getItem('SURNAME');
document.getElementById('result-name').value = name;
document.getElementById('result-surname').value = surname;
})
</script>
</head>
<body>
<h1>
Result Page
</h1>
<h2>
Name: <input id="result-name" />
</h2>
<h2>
Surname: <input id="result-surname" />
</h2>
</body>
</html>
Read on local storage vs session storage. They are bit different.

input field won't clear up

I can't clear up my input field even tho i followed a tutorial step by step , i'm making this to do list and I want the input field to be clear anytime i submit a new to do . so what is wrong with my code ?
ps : i tried to clear the cache and nothing
let addButton=document.getElementById('addButton');
let toDoContainer = document.getElementById('ToDoContainer');
let inputField = document.getElementById('text');
//event listeners
addButton.addEventListener('click',addTodo);
//functions
function addTodo(event,title){
event.preventDefault();
//create the to do
let toDoDiv = document.createElement('div');
toDoDiv.classList.add('todo');
const newToDo =document.createElement('p');
newToDo.innerHTML=inputField.value;
newToDo.classList.add('todo-item');
toDoDiv.appendChild(newToDo);
toDoContainer.appendChild(toDoDiv);
//check mark button
const completedButton = document.createElement('button');
completedButton.innerHTML="success";
completedButton.classList.add("complete-btn");
toDoDiv.appendChild(completedButton);
//check delete button
const trashButton = document.createElement('button');
trashButton.innerHTML="delete";
trashButton.classList.add("complete-btn");
toDoDiv.appendChild(trashButton);
//append todo
toDoContainer.appendChild(tododiv);
inputField.value= "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>to do list </title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="container">
<header>
<h1>This is your to do list </h1>
<div class="input">
<input type="text" placeholder="what to do ...?" id="text">
<input type="button" value="add" id="addButton">
</div>
</header>
<div id="ToDoContainer">
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
here is a screenshot
sonEtLumiere is right, you have a typo. It should be:
toDoContainer.appendChild(toDoDiv);
Your variable is called toDoDiv, you have an error in this line (penultimate line):
toDoContainer.appendChild(tododiv);
This will work:
toDoContainer.appendChild(toDoDiv);

I'm receiving an uncaught type Error when looping using .add() in a loop

Once I have rendered my template with my elements I wanted to add options with values dynamically from JSON data, it populates and works fine but gives me: Uncaught (in promise) TypeError: sel.add is not a function
I have tried and failed to use a different set-up with .appendChild and it's doing me. I can't see the issue but I haven't been using JS long enough to know hope someone can help.
...js
const csv = require('csvtojson');
const path = "filepath here";
readData(path);
async function readData(path){
const data = await csv().fromFile(path).on('header', (header) =>{
assign(header);
});
}
function assign(col){
//Renders Template
const contain = document.getElementById("container");
const temp = document.getElementById("dropdown").content;
const clone = temp.cloneNode(true);
contain.appendChild(clone);
populate(col);
}
function populate(col){
//Populates dropdown boxes with data from headers
const group = document.querySelectorAll('.choice');
for(let i in group){
for(let x in col){
let sel = document.getElementsByClassName('choice')[i];
let opt = document.createElement('option');
opt.text = col[x];
opt.value = col[x];
sel.add(opt, sel[x]);
}
}
}
...
...html
<!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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Bulk Upload Assistant</title>
</head>
<body>
<div id="container">
<h1>Please browse to upload file</h1>
<input type="button" id = "browse-files" value="Browse" >
<template id="dropdown">
<p>Please select the appropriate headings for your file</p>
<p class = "drop-down">ID field</p>
<p class = "drop-down">Leaver field</p>
<p class = "drop-down">Auth Type field</p>
<select id="ID" class = "choice">
</select>
<select id="LEAVE" class = "choice">
</select>
<select id="AUTH" class = "choice">
</select>
<button onClick = 'getHeadings()'>Submit</button>
</template>
</div>
<script src = 'render.js'></script>
</body>
</html>
...
Should not throw the error message

Categories

Resources