Javascript, div on click multiple numbers in input field - javascript

I'm trying to create a JavaScript to modify the number in my input field.
Example:
<input value="0">
And then a simple button or div with a JavasSript click function.
<button>Add +10</button>
After clicking on the button:
<input value="10">
Does someone have a place I can read and learn to create this, or any tips to get me started. I know very little JavaScript, but I wish to learn.

Try this or fiddleLink.
ParseInt helps in converting the string value to numbers and add them instead of concatenating. Let me know if you still have some trouble.
var tag1Elem = document.getElementById("tag1");
// The callback function to increse the value.
function clickFN() {
tag1Elem.value = parseInt(tag1Elem.value, 10) + 10;
}
// Reset the value back to 0
function resetFN() {
tag1Elem.value = 0;
}
// Callbacks can be attached dynamically using addEventListener
document.getElementById("btn").addEventListener("click", clickFN);
document.getElementById("reset").addEventListener("click", resetFN);
#wrapper {
margin: 20px;
}
<p>This is a basic tag input:
<input id="tag1" value="0" />
<button type="button" id="btn">Add +10</button>
<button type="button" id="reset">Reset</button>
</p>

You can try this
<input value="0" id="id">
give a id to input field
on button click call a function
<button onclick="myFunction()">Add +10</button>
<script>
function myFunction() {
document.getElementById("id").value = parseInt(document.getElementById("id").value) +10;
}
</script>

You can use a click counter like this
and edit it replacing += 1 with += 10.
Here my code,
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.addEventListener("click", function()
{
clicks += 10;
input.value = clicks;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Script</title>
</head>
<body>
<input id="valor" value="0">
<button id="buttonvalue">10</button>
</body>
</html>

Related

Why the button object can not use the onclick() function?

I am trying to use javascript to create a web calculator. I hope that users can calculate the result when they click the different buttons. However, there is an error in line16(Uncaught TypeError: Cannot read property 'onclick' of null). I hope someone could help me. These are my codes:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var btnadd,btnsub,btnmul,btndiv;
btnadd = document.getElementById('btnadd');
btnsub = document.getElementById('btnsub');
btnmul = document.getElementById('btnmul');
btndiv = document.getElementById('btndiv');
btnadd.onclick() = function(){
cal(add());
}
function cal(func){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
parseFloat(num1);
parseFloat(num2);
var result;
result = func(num1,num2);
document.getElementById('result').value = result;
}
function add(num1,num2){
return (num1+num2);
}
function sub(num1,num2){
return (num1-num2);
}
function mul(num1,num2){
return (num1*num2);
}
function div(num1,num2){
return (num1/num2);
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="num1" /><br>
num2:<input type="text" id="num2" /><br>
<input type="button" id="btnadd" value="add" />
<input type="button" id="btnsub" value="sub" />
<input type="button" id="btnmul" value="mul" />
<input type="button" id="btndiv" value="div" /><br>
result:<input type="text" id="result"/>
</form>
</body>
</html>
You need to either add the defer attribute to your script or put it at the end of the body.
Putting JS code in the head means that it will be run before the page is fully parsed. That means that there is no element with the id of btnadd just yet. If you add the defer attribute, then it will wait for the page to be parsed before running the script. Putting at the end of the body has the same effect.
In terms of your code itself, you need to set the onclick property. You cannot assign a function like that. Also, do val2 = parseFloat(val2) rather than parseFloat(val2). (similarly for val1) because here you need to reassign the value
Because you didn't define the onclick correctly
Instead of
btnadd.onclick() = function(){
cal(add());
}
try
btnadd.onclick = function(){
cal(add);
}
Check this codepen : https://codepen.io/zecka/pen/NWrejxO
Note that there are other errors in your code that will prevent you from making it work as you want.

How can you add and multiply the values of a textbox in javascript?

I am trying to add the first two textboxes and then multiply the last one to that value and put that into a textbox but I am getting nowhere please help.
Unclear.
You can give the three textboxes an id and create a variable.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<input id="firsttextbox"></input>
<input id="secondtextbox"></input>
<input id="thridtextbox"></input>
<button onclick="calculate()">Calculate</button>
</body>
</html>
var firstTextbox = document.getElementById('firsttextbox');
var secondTextbox = document.getElementById('secondtextbox');
var thirdTextbox = document.getElementById('thirdtextbox');
Add the firstTextbox value and secondTextbox value and then multiply by third text box
function calculate() {
var sum = firstTextbox.value + secondTextbox.value;
var final = sum * thirdTextbox.value;
}
you need to check each time there's a change in the document. you want to make sure that the user has entered a valid number in the first three text areas
document.addEventListener("change", myScript);
function myScript(){
var texts = document.getElementsByTagName('textarea');
var cnt = 0;
for(let i = 0;i<3;i++){
if(!isNaN(texts[i].value) && texts[i].value!='')cnt++;
console.log(cnt);
}
if(cnt == 3){
texts[3].value = (parseFloat(texts[0].value)+parseFloat(texts[1].value))*parseFloat(texts[2].value);
}
}
<textarea id='a1'></textarea>
<textarea id='a2'></textarea>
<textarea id='a3'></textarea>
<textarea id='a4'></textarea>
<center>
<input type="text" id="t1" name="fname"><br>
<input type="text" id="t2" name="lname"><br>
<input type="text" id="t3" name="lname"><br>
<input type="button" onclick="script:
var out=t1.value+t2.value*t3.value;
alert(out);
"value="Test It Out!!">
</center>

How to create a DIV onclick using only JavaScript?

<!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" type="text/css" href="style.css">
<title>Etch-A-Sketch</title>
</head>
<body>
<h1>Etch-A-Sketch</h1>
<p id="Grid-Size">Grid Size</p>
<form onsubmit="getTotalGridSize()"> <!--onsubmit has to be on the form tag not the submit input-->
<input type="number" placeholder="size" min="1" max="100" id ="size" value="" oninput="getSizeValue()">
<input type="submit" id="Submit" value="Submit" onclick="createTile()">
</form>
<p id="Colors">Choose Color</p>
<form id="color-options" >
<input type="radio" name="choice" value="blue">
<label for="default">Default</label>
<input type="radio" name="choice" value="random" >
<label for="random">Random</label>
<input type="radio" name="choice" value="white" >
<label for="white">White</label>
<input type="radio" name="choice" value="user" >
<label for="color-picker">Color Picker</label>
<input type="color" id="color-picker" value="">
</form>
<div id="Sketch">
<div id="tile" onmouseover="updateHoverColor()">
</div>
</div>
<script src="etch.js" charset="utf-8"></script>
</body>
</html>
//Dom Accessed Variables
let tile = document.getElementById("tile")
let sizeValue = null
let gridSize= null
let containerDiv = document.getElementById("sketch")
//input functions
function getSizeValue() {
sizeValue = document.getElementById('size').value //getting the inputs value
}
function getTotalGridSize() {
gridSize = sizeValue * sizeValue
}
//Generates random RGB values
function randomColor() {
let red = Math.floor(Math.random() * 255 + 1);
let blue = Math.floor(Math.random() * 255 + 1);
let green = Math.floor(Math.random() * 255 + 1);
//Returns string with style to be applied
let random = `rgb(${red}, ${green}, ${blue})`;
tile.style.backgroundColor = random;
}
function updateHoverColor() {
let colorChoice = document.getElementById("color-picker").value
if(document.querySelector('#color-options > input:checked').value === "blue") {
tile.style.backgroundColor = "blue"
} else if (document.querySelector('#color-options > input:checked').value === "random") {
randomColor()
} else if (document.querySelector('#color-options > input:checked').value === "white") {
tile.style.backgroundColor = "white"
} else if (document.querySelector('#color-options > input:checked').value === "user") {
tile.style.backgroundColor = colorChoice;
}
}
function createTile() {
let baby = document.createElement("div");
baby.style.height = "200px"
baby.style.width = "100px"
baby.style.backgroundColor = "black"
document.body.appendChild(baby)
}
What I'm trying to do is have another div be created inside its container div after the user clicks on the submit button. I created a function using JavaScript which does that and then attached it to onclick on that same button. I even followed the exact same syntax to create the function from W3schools to create and append and element but it doesn't seem to be working at all in my code, and I'm trying to figure out why.
Your submit button within the first form has an onclick, but the containing form also has an onsubmit. That's going to cause some inconsistent behavior with respect to what functions are firing and when. Stick with the form onsubmit. I also recommend not attaching the event listener with HTML, but to give the form an ID and then attach the event listener through the ID.
// HTML
<form id="totalGridSizeForm">
// JavaScript
const gridSizeForm = document.getElementById("totalGridSizeForm");
gridSizeForm.addEventListener("submit", (event) => {
event.preventDefault();
// Whatever logic you need goes here
});
Main problem with your application is that when you submit some form, information is sent and page refreshes, your div is probably being created but later deleted because of page reload.
The best option is to save certain condition inside LocalStorage and everytime after refresh If page meets special conditions divs will be shown. Here is the example:
function saveInformation(func) {
var funcs = [
'size',
'save'
]
if (func==funcs[0]) {
sizeValue = document.getElementById('size').value;
}
if (func==funcs[1]) {
localStorage.setItem('saveCheck','true');
}
return false;
}
function check() {
var saveCheck = localStorage.getItem('saveCheck');
if (saveCheck == 'true') {
generateDIV();
}
}
function generateDIV() {
let element = document.createElement("div");
element.style.height = "200px";
element.style.width = "100px";
element.style.backgroundColor = "black";
document.body.appendChild(element);
}
document.addEventListener('DOMContentLoaded',function() {
check();
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/html/b.js"></script>
<title>Document</title>
</head>
<body>
<form>
<input type='number' placeholder='Number' id='size'>
<input type='submit' onclick='saveInformation("size");saveInformation("save");'>
</form>
</body>
</html>
EDIT: I could not save to Local Storage from Stack Overflow Code snippet, so you will need to test this code from an editor
What I did is that I disabled submit button with 'return false' but we are still getting information from input values, just without reload and with the shown div.
So idea is to have an fucntion that saves information from input value and saves bool called 'saveCheck' into the local storage. If the given 'saveCheck' from the local storage is true we are going to call 'generateDIV()' and from there we will have that div loaded every time page refreshes.
This is an example with pure Javascript, but I suggest you start using JQuery if haven't already.
Hope I helped!

NaN, when running BMI calculator

What am i doing wrong? According to the textbook example this is supposed to be sufficient code, but I get NaN when running it in a browser.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8"/>
<html>
<head>
<title>test</title>
</head>
<body>
<p>Vekt: <input type="text" id="txtVekt" /></p>
<p>Hoyde: <input type="text" id="txtHoyde" /></p>
<button id="btnBeregn">Beregn</button>
<p id="resultat"></p>
<script>
window.onload = beregn();
function beregn(){
var hoyde = document.getElementById("txtHoyde").value;
var vekt = document.getElementById("txtVekt").value;
var bmi = vekt / (hoyde * vekt);
document.getElementById("resultat").innerHTML = "Din BMI er: " + bmi;
}
</script>
</body>
</html>
Your values are not initialized when you first run the function
There's really no need to run the function onload, especially
since your values aren't initialized. Note that my code removes the onload invocation.
You can just run the calculation when the button is clicked. You might also want to add some validation before you run the function, but I'll leave that exercise to you.
<body>
<p>Vekt: <input type="text" id="txtVekt" /></p>
<p>Hoyde: <input type="text" id="txtHoyde" /></p>
<button id="btnBeregn" onclick="beregn();" >Beregn</button>
<p id="resultat"></p>
<script>
function beregn(){
var hoyde = document.getElementById("txtHoyde").value;
var vekt = document.getElementById("txtVekt").value;
//this assumes your inputs are valid numbers...
var bmi = vekt / (hoyde * vekt);
document.getElementById("resultat").innerHTML = "Din BMI er: " + bmi;
}
</script>
</body>
hoyde and vekt do not have any value when the page loads since the inputs are empty, so there is no reason why bmi should give you anything other than NaN.
You need to either give those inputs a default value (probably 1 to begin) and then rerun the begregn function whenever the button is clicked:
<p>Vekt: <input type="text" id="txtVekt" value=1/></p>
<p>Hoyde: <input type="text" id="txtHoyde" value=1/></p>
<button id="btnBeregn" onclick="begregn()">Beregn</button>
Or just don't run begregn on window load, but only when the button is clicked
window.onload runs... on window load. :)
Change window.onload = beregn(); to:
var btn = document.getElementById("btnBeregn");
btn.addEventListener("click", beregn);

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