I want the programme to get the biggest number that the user has enter in one of the input boxes and display the bigger number to the user.I would also like some improvements to my code. I would it also be possible to do it with one input box instead of two
<!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>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button >Submit</button>
<div id="store"></div>
<script>
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
function max(){
const element = document.createElement('div');
const num1 = box1.value;
const num2 = box2.value;
if (num1<num2 ){
element.innerHTML= num2;
store.appendChild(element);
}
if (num2<num1){
element.innerHTML= num1;
store.appendChild(element);
}
}
</script>
</body>
</html>
First of all, ECMAScript comes with a Math.max() function, so there is no need to re-implement that comparison logic.
Also, your max function doesn’t run automatically. You need to register it as an event listener on the “Submit” button using addEventListener and the click event in order to have it invoked upon clicking the button.
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
const store = document.getElementById('store');
const button = document.getElementById('submit');
// upon clicking on the button …
button.addEventListener('click', () => {
max(); // … run `max()``
});
function max() {
const element = document.createElement('div');
element.innerText = Math.max(box1.value, box2.value);
store.appendChild(element);
}
<h1>Max number</h1>
<input id="box1" placeholder="Enter the fist number" type="number">
<input id="box2" placeholder="Enter the second number" type="number">
<button id="submit">Submit</button>
<div id="store"></div>
Of course, there is not yet a validation that checks if the given values are actually numbers.
I don’t understand your request about doing it with only “one input box”, though, as determining the larger number (out of many) implies having more than one input, so please specify. Do you mean “multiple values in one input box” like comma-separated?
Yes, you can do it all in one input please see the code below
<!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>Get largest number</title>
</head>
<body>
<input type="text" class="myinput" placeholder="Enter your numbers seperated by commas only">
<button class="submit">Get Max</button>
<h1 class="output"></h1>
<script>
const inputElement = document.querySelector('.myinput');
const submitButton = document.querySelector('.submit');
const outputElement = document.querySelector('.output')
submitButton.onclick = function(){
let inputValue = inputElement.value;
if(inputValue !== ''){
try{
let numbers = inputValue.split(',').map(e=>eval(e));
const maxNumber = Math.max(...numbers);
outputElement.innerHTML = 'Largest Number: ' + maxNumber;
}catch(e){
outputElement.innerHTML = 'Incorrect input format!';
}
}
}
</script>
</body>
</html>
The code takes comma separated input from the user and converts it into an array using the split function. Each value separated by the comma will be an array item. I also mapped it to convert the numbers that were in string form to integer form using the eval function. then I used the try catch block to detect any input format errors that may occur that the program will not be able to process and push an error to the user that they have used the incorrect format.
I hope that helps alot!
Related
I'm using JavaScript to make divs when the user clicks a button. This part is working fine. It creates a form with two buttons, make, and delete shot. Make doesn't work right now- I'm just building out the front end. The delete shot button should just delete it's parent div and everything in it- but clicking any of the delete buttons deletes all of the divs! Sorry if I'm not explaining this well.
Here is my HTML:
<!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>
<script src="./app.js" defer></script>
</head>
<body>
<h1>Calypso</h1>
<p>Use Calypso to make storyboards: </p>
<div class="newShot"></div>
<button class="newShotButton">New Shot</button>
<button
</body>
</html>
And here is my JavaScript:
let container = document.querySelector(".newShot")
let btn = document.querySelector(".newShotButton")
let shotListArray = []; //holds all of the shot objects
class shotObject {
constructor (number) {
this.name = ("shot" + number);
this.htmlContent =`
<form class="shot${number}"
<fieldset>
<legend>Shot ${number}:</legend>
<label for="fname">Enter Shot Description:</label><br>
<textarea id="fname" name="fname"> </textarea><br>
<input type="submit" value="Make">
<input type="submit" value="Delete shot" class="shot${number}DeleteButton">
<script>
let deleteShot${number} = document.getElementByClass('shot${number}');
shot${number}DeleteButton.addEventListener ("click", deleteShot${number}.remove());
</script>
</fieldset>
</form>
`
}
}
function createNewShot(){
let newShot = new shotObject (shotListArray.length + 1);
shotListArray.push(newShot);
let arrayLength = shotListArray.length
container.insertAdjacentHTML("beforeend", shotListArray[arrayLength-1].htmlContent);
}
btn.addEventListener("click", createNewShot);
I just want the delete buttons to work as expected. I'm a little confused because when I look at the live server, I can see the class names are correct in the tags for each of the buttons.
I am writing a function that should change the color of an h1 tag based on the value of the text in a text input form field. My HTML and JavaScript code is below:
function checkIfZero() {
//Get relevant elements from dom.
let value = parseInt(document.getElementById('text-field'));
let heading = document.getElementById('heading');
//Check if the element is zero, if so, adjust the color of the H1
if (value === 0) {
heading.style.color = 'green';
} else {
heading.style.color = 'red';
}
}
//Bind the function to onsubmit.
let form = document.getElementById('my-form');
form.onsubmit = function() {
checkIfZero();
};
<!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>
<script src='throwaway.js' type='text/javascript' defer></script>
<h1 id='heading'>This is a heading</h1>
<form id='my-form'>
<input type='text' id='text-field'>
<input type='submit' id='submit'>
</form>
</body>
</html>
Here, if I type in the number 0 in my input field and press enter (or click Submit), the color of the h1 tag does not change. However, I did check if the event was triggered or not.
When I amend my event listener to this:
let form = document.getElementById('my-form');
form.onsubmit = function() {
alert('You submitted the form');
};
, the alert does pop up in the browser. This suggests that there is an issue with my checkIfZero() function and not necessarily binding the function to the form element.
May I know how to fix my function so that it does change color upon firing the submit event? Thank you.
this is my code:
"use strict";
const searchBox = document.querySelector("#myText");
const searchBtn = document.querySelector(".btn-search");
const searchContainer = document.querySelector(".search-container");
let mainText = document.querySelector(".main-text");
const quit = document.querySelector("#btn-close");
let showMain;
const newMain = "";
let printMain = function(text) {
showMain = `
<article class="country">
<h1>Country you Searched</h1>
<p>Hello</p>
<p>${text}</p>
</article>`;
console.log(`Our show main is : ${showMain}`);
mainText.insertAdjacentHTML("beforeend", showMain);
};
searchBox.addEventListener("click", function() {
if (searchBox.value === "Type in") {
searchBox.value = "";
}
});
searchBtn.addEventListener("click", function() {
if (searchBox.value && searchBox.value !== "Type in") {
console.log(searchBox.value);
printMain(searchBox.value);
searchBox.value = "";
} else {
alert("please type in country name!");
}
});
quit.addEventListener("click", function() {
//mainText.remove(showMain);
const myDiv = document.getElementById("myId");
const parent = myDiv.parentNode;
parent.removeChild(myDiv);
console.log(showMain);
});
<!DOCTYPE html>
<html lang="en">
<header>
<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 defer src="script.js"></script>
<title>Simple Work</title>
<button id="btn-close">go back</button>
</header>
<body>
<main class="container">
<div class="main-text" id="myId"></div>
<p class="search-container">
<label>Type In : </label>
<input type="text" id="myText" value="Type in" />
</p>
<button class="btn-search">input</button>
</main>
</body>
</html>
So, I was trying to make code that add the text using insertAdjacentHTML
and next when I click "go back" button, it will erase the html that I had added using insertAdjacentHTML.
I have success up to this point. After this when I try to add new HTML using insertAdjacentHTML, it doesn't work. What I must do to fix this?
(as my English is second language, explanation might not be clear, I am just making web site that I could add text(must use insertAdjacentHTML) and erase that by using "go back" button and after I erase all of them, it could add new text again by using "input" button)
When you remove the node, you are removing the element that mainText points to, therefore, you code cannot place content into a node that is no longer there. So it throws an error stating so.
You should probably only remove the element with classname of country:
document.querySelector('.country').remove();
I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
And the Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it.
An image of the console log:
https://imgur.com/a/AiV4hRM
I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.
You need to get the value of the input from value attribute.
The below code will just return the reference to the input not the value.
var inputText = document.getElementById("inputBox");
To get the value of the input, you need to get it from the value attribute.
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
Working Example:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
You are pretty close, just missing that you need to get the value attribute of the textbox. See working example below.
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText.value);
console.log(customList);
});
<input id="inputBox" />
<button id="addButton">Add</button>
Ok, this might be quite hard for me to explain, but I will give it a go. I have two HTML pages: form.html & display.html. The form page has an input which obtains a value and then puts it into local storage once the form is submitted. After the form submission, the user will be taken to the display page, which will then retrieve the input value from the previous page from local storage and then displays the value inside the input field on the display page. The display page will later act as a job page which will display a list of jobs which is filterable by the value inside the input field on the same page. I can get the filter function to work by using onkeyup on the input field, but I what I can't make work is the filter function with the input value from the previous page by using something like onload. The reason why I am using two pages is that I will later use this code on a website which will have a search box on the landing page, and then will be directed to the Jobs page with filtered results. I am sorry if this was really hard to understand, I will post the code below so you might better understand.
Many thanks to anyone who takes time out of their day to help me with this problem, it is much appreciated.
form.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">
<title>Document</title>
<script>
function passValues() {
var firstName = document.getElementById("txt").value;
localStorage.setItem("textValue", firstName);
return false;
}
</script>
</head>
<body>
<form action="display.html">
<input type="text" id="txt" />
<input type="submit" value="Click" onclick="passValues();" />
</form>
</body>
</html>
display.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">
<title>Document</title>
</head>
<body>
<h1>Tokyo Expat Job Search</h1>
<input onload="filter()" onkeyup="filter()" id="result" type="text">
<ul id="Menu">
<li>English Techer</li>
<li>Waiter/Waitress</li>
<li>Developer</li>
<li>Banker</li>
<li>Designer</li>
<li>Logistics</li>
</ul>
<script>
function filter() {
var filterValue, input, ul, li, a, i;
input = document.getElementById("result");
filterValue = input.value.toUpperCase();
ul = document.getElementById("Menu");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filterValue) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
document.getElementById("result").value = localStorage.getItem("textValue");
</script>
</body>
</html>
Try to add the listener to window.onload? The input does not have such an event.
window.addEventListener('load', filter, false)