DOM is receiving empty strings - javascript

so i have been trying make a calculator webpage just to get used to DOM, but for some reason when i try to get user input i receive empty strings.
this is my html
<!DOCTYPE html>
<html>
<head>
<title>Calculator DOM Practice</title>
</head>
<body>
<h1>Welcome to Calculator Web page</h1>
<!-- <form> -->
<div class="prompts">Please enter your first number</div>
<input id="first_num" type="text" placeholder="first num"><br>
<div class = "prompts">Please enter second number</div>
<input id="second_num" type = "text" placeholder="second num"><br>
<label for="operator">Chose your operation: </label>
<select id="operator" name = "operator">
<option value ="minus">-</option>
<option value ="addition">+</option>
<option value ="multiply">*</option>
<option value ="divide">/</option>
</select>
<button id="calc_button" type="submit">Calculate</button>
<!-- </form> -->
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
and here is my javascript where i receive the user input:
var first = document.getElementById("first_num").value;
var second = document.getElementById("second_num").value;
// var oper = document.getElementById("operator").value; //this only give sme
first index
var oper = operator.options[operator.selectedIndex].value;
var button = document.getElementById("calc_button");
first = Number(first);
second = Number(second);
I have tried using document.getElementId("first_num").text but for some reason it as if my script runs as soon as the webpage is started, so it sets those variables when they are empty.

As you said this script is looking for the empty input value when the page is first rendered. You need to add an event lister which calls a function when the input value is updated.
var firstInput = document.getElementById("first_num");
var firstNumber;
function updateFirstNumber(e) {
firstNumber = e.target.value;
}
first.addEventListener('change', updateFirstNumber);
More information on events (MDN)

Related

The inputs are not showing up at all when I click on the button. If I remove the form an html then it works but I want it to work in form

I know this may be a dumb question to some but I am pretty new to this and trying to learn. I have been stuck on this for days and couldn't figure it out so I came here for help. Whenever I hit the button it doesn't display my input at all. I want to make it that when the user clicks the button their input will show up in an ol list.
let form = document.getElementById("todo");
let list = document.getElementById("myList");
let input = document.getElementById("add1");
let input2 = document.getElementById("add2");
let button = document.getElementById("button");
let id = 1;
button.addEventListener("click", addToDo)
list.addEventListener("click", removeEvent)
function addToDo (e) {
let text = input.value;
let textAdd = input2.value;
let item = `<li class="del">
${text} ============= ${textAdd} <button class="del">Delete</button>`
list.insertAdjacentHTML("beforeend",item);
id++;
document.getElementById("add1").value = "";
document.getElementById("add2").value = "";
}
function removeEvent(e) {
if(e.target.classList.contains("del")) {
list.removeChild(e.target.parentElement);
list.removeChild(list);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1 id="name">Todo List</h1>
<link href="project.css" rel="stylesheet"/>
</head>
<body>
<div id="todo">
<h1>Name</h1>
<input type="text" id="add1" placeholder="Title">
<br>
<h1>Add Reminder</h1>
<input type="text" id="add2" placeholder="Notes">
<button id="button">Submit</button>
</div>
<ol id="myList">
</ol>
<script src="pro.js"></script>
</body>
</html>
There is something "special" about buttons within a form.
If your HTML looks like:
<form>
<input placeholder="enter some text">
<button>Click me</button>
</form>
Your button will submit the form and therefore reset it.
I guess you would expect the form to have some crucial properties to do so, namely 'action' and 'method' (to send the data in your inputs to some remote address - because that's the main concern of forms).
If you want your button to just be a button, use the following:
<form>
<input placeholder="enter some text">
<button type="button">Click me</button>
</form>
And you'll see: nothing happens.
I've created a StackBlitz here for you (just look at the HTML file). With type="button", more and more inputs are added to the form. If you omit this, you can see the input is added, and immediately after it, the form resets itself (sending a GET request to '/' and refreshing everything - but that's something for another question).

Change the first and second text input value when they don't have an ID

I know how to change the text input value with javascript if they have IDs, but what if they don't have IDs? I need to find and change the value of the first, and second text input on the page. How would I do that?
<input type="text" id="text" value="no value">
<button onclick="myFunction()">Change Values</button>
function myFunction() {
document.getElementById("text").value = "Text is now changed";
}
I need to know how to change the first and second input text's value on the page if they don't have an ID. For example, change "no value 1" to "yes value 1", and "no value 2" to "yes value 2". How would I do that?
<input type="text" value="no value 1">
<input type="text" value="no value 2">
If i understand your question correctly, using document.getElementsByTagName is one answer.
const inputElements = document.getElementsByTagName('input');
inputElements[0].value = "insert input 1";
inputElements[1].value = "insert input 2";
check this jsfiddle (https://jsfiddle.net/hentleman/09tr7bku/1/)
Old school, but still works:
function changeEm() {
document.forms[0][0].value = "yes value 1";
document.forms[0][1].value = "yes value 2";
}
<body onload=changeEm()>
<form>
<input type="text" value="no value 1">
<input type="text" value="no value 2">
</form>
</body>
There are many document elements query methods, one of them is document.getElementsByTagName.
This method returns an HTMLCollection, which is an iterable of HTML objects.
Having this knowledge, let's say you have the following HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Get Inputs</title>
</head>
<body>
<input type="text" value="First" />
<input type="text" value="Second" />
</body>
</html>
You could get all the input elements in your HTML using document's getElementsByTagName as follows:
const inputEls = document.getElementsByTagName("input");
inputEls will contain a HTMLCollection of HTMLInputElement, now we are able to iterate the collection and do something with it.
The final JavaScript must look like the following:
const inputEls = document.getElementsByTagName("input");
for (let input of inputEls) {
// Here you are able to access every input element of te collection
// And consume HTMLInputElement object
console.log(input.value);
}

How do I take user input and link to corresponding HTML page using JavaScript?

So, I have a form on my HTML page, and a separate button that links to the form. My question is: when the user enters a certain input (in this case a string) and clicks on the button, how do I connect the user to a different HTML page based on the corresponding user input from the form? I know I have to use javascript, but any specific code will be extremely helpful. Thanks!
ADDDED MY CODE:
<!doctype html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form id = "user-info" onSubmit="myFunction()">
<div class = "favorite-fruit">
<p>Enter your favorite fruit<br></p>
<input type="text" name="fav-fruit" id = "fruit"><br>
</div>
<div class="favorite-vegetable">
<p>Enter your favorite vegetable<br></p>
<input type="text" name="fav-vegetable" id="vegetable">
</div>
</form>
<a class = "confirm" onSubmit="myFunction()">
<button form= "user-info" type="button" name= "confirm-input">Confirm</button>
</a>
</div>
<script type="text/javascript">
function myFunction(){
var firstFruit = document.getElementById("fruit").innerHTML;
var secondVegetable = document.getElementById("vegetable").innerHTML;
var f = firstFruit;
var s = secondVegetable;
if(f.value == "Apple" && s.value == "Broccoli"){
//GO TO "appleBroccoli.html"
}
else if(f.value == "Grapes" && s.value == "Carrots"){
//GO TO "grapesCarrots.html"
}
else if(f.value == "Strawberry" && s.value == "Kale"){
//GO TO "strawberryKale.html"
}
}
</script>
</body>
</html>
It can be done by taking up the value of input tag like :-
var value = $(element).val();
Then resetting the action attribute of the form tag with the new value like :-
$(formElem).attr("action",value+".html")
I guess this would help u..
Your form, user-info doesnt have a submit button
add <input type = 'submit' name='conform'>Confirm</input> inside the form
Set action and method to the form to the corrosponding target HTML page.
<form action='..target html' method ='get'>
</form>
If the input is brocolli, you can change the form action as
document.getElementById('user-info').action = <new target>

Select the value of a form - JavaScript

I am new to JavaScript and I am trying to understand HOW the code works.
In my form I have two inputs:
First Name: which has to be filled by the user
Countries: which has to be selected by the user (but the countries are already there)
Once the user click the "Add this destination" button, it should appear his name plus the destination he has chosen.
I understand why the "destination" appears.
HOWEVER I do not understand HOW the first name can be passed if the form is empty. Even if I write something in "first name", its value is not passed into the result string I want to display.
My questions are two:
1) Why is not my code working?
2) MORE IMPORTANTLY: how the browser (?) understands that there has been a change in the filed of "first name" from empty to be filled with a name/string?
var x;
var destination = document.myTravelForm.destination.value;
var firstName = document.myTravelForm.firstname.value;
x = document.getElementById("banana").addEventListener("click", function() {
document.getElementById("travelerInfo").innerHTML = firstName + " you chose: " + destination
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname" /><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana" />
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
You need to get the form values when you are clicking on the button, if you get them before click, you will get their initial values. Try something like this:
var x;
x = document.getElementById("banana").addEventListener("click", function() {
var destination = document.myTravelForm.destination.value;
var firstName = document.myTravelForm.firstname.value;
document.getElementById("travelerInfo").innerHTML = firstName + " you chose: " + destination;
});
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname" /><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana" />
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Matheus Pitz answered your first question fine, the variables are initialzed at the beginning of the script where they are undefined.
As for your second question how does the browser understand that there has been a change. The browser has several build in technologies that work together to allow this.
First your HTML documents are parsed by a browser and it will show a Javascript model of it which consists of various nodes. This is called the DOM (document object model).
The browser has all sorts of built in JS functions to manipulate the DOM and thus manipulate the view. For example:
document.getElementById("travelerInfo").innerHTML = 'test';
getElementById() Is an example of such a method which allows you to access a DOM node and perform various operations on it.
Hopefully this was helpful and I would strongly suggest you to read MDN article about the DOM. This will increase your understanding and make you a better developer.
For first part:
Because you're getting the value before it's event entered
Put that code inside your click callback.
2nd part
I don't really understand what do you mean by "How does browser...". You just get the value out of input
var destination = document.myTravelForm.destination;
var firstName = document.myTravelForm.firstname
document.getElementById("banana").addEventListener("click", function() {
document.getElementById("travelerInfo").innerHTML = firstName.value + " you chose: " + destination.value
});
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname"/><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana"/>
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

generate textboxes based on number enter by user

I want when a user enter number in the textbox and click set, textboxes appear based on the number he entered and this what I come up with but it is not working please help
<html>
<head>
<script>
function generate(){
var a=parseInt(document.getElementById("nochapter").value);
for (i=0;i<=a,i++){
document.getElementById("ch").innerHTML="<input type='text' >"}}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included <input type="text" id="nochapter" >
<input type ="button" value="set" onclick="generate()">
<div id="ch"></div>
Your code should be like this.
Is better append an input element to the div.
<head>
<script>
function generate() {
var a = parseInt(document.getElementById("nochapter").value);
var ch = document.getElementById("ch");
for (i = 0; i < a; i++) {
var input = document.createElement("input");
ch.appendChild(input);
}
}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included
<input type="text" id="nochapter" />
<input type="button" value="set" onclick="generate()" />
<div id="ch"></div>
</form>
</body>
There is small glitch in your written code
for (i=0;i<=a,i++) --> for (i=0;i<=a;i++)
even if you change that it will generate only one text box because you are replacing innerHTML for every iteration. so prepare the string separately based on no of iteration and assign it to innerrHTML. it should work.

Categories

Resources