How to create a DIV onclick using only JavaScript? - 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!

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.

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).

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>

Javascript, div on click multiple numbers in input field

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>

I have a form with radio buttons inside an iframe inserting text to parents textarea. "Undefined" comes to texarea instead of radio buttons value

If I make a form, and add an ONSUBMIT to that it gives UNDEFINED as an answer to the parent window "textarea" instead of a value from the RADIOBUTTON that is chosen. I would not want to change the javascript, because it works fine with a that has onclick with a value, but is it possible to get the to work with the same script? Or what should I do to make this work?
here is an example of my work:
index.html:
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function hello(string){
// get the current text, add a newline if not blank, and append new
// text
var anchorText = document.getElementById('myAnchor').value;
if(anchorText !== "") anchorText += '\n';
anchorText += string;
document.getElementById('myAnchor').value=anchorText;
}
</script>
<title>joubadou</title>
</head>
<body>
<form>Cart<br>
<br>
<textarea rows="10" id="myAnchor"></textarea></form>
<iframe src="radiobuttontest.html" height="300"></iframe>
</body>
</html>
radiobuttontest.html:
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
</head>
<body>
<br>
<form id="myForm" action="" method="get"
onsubmit="parent.hello()">If
you want a blue
car you can choose<br>
<br>
<input name="sex" value="Bensin" checked="checked"
type="radio">Bensin<br>
<input name="sex" value="Diesel" type="radio">Diesel<br>
<br>
<input value="add to cart"
onclick="parent.hello('Blue car')" type="submit"></form>
<br>
</body>
</html>
If you please can help me I would be so clad!
This is what happens when user clicks add to cart:
The onclick of the input fires, and the value of #anchorText is
changed to 'Blue car', which is passed to hello().
onsubmit fires from the form, and the value of #anchorText is
changed to undefined, since string is not passed.
To fix this, just remove the onsubmit attribute from the form, and pass the radio buttons instead of a string, for example:
Add this if to the hello():
function hello(string){
if (typeof string === 'object') { // Checks if an object is passed instead of a string
for (var n = 0; n < string.length; n++) { // Iterate through object
if (string[n].checked) { // Check, if the current radio button is checked
string = string[n].value; // Change the value of string to value of checked radio button
break;
}
}
}
var anchorText = document.getElementById('myAnchor').value;
:
}
and pass the radio buttons like this:
<input value="add to cart" onclick="parent.hello(document.getElementsByName('sex'));" ... />
Notice, that you still can use hello() to handle also strings, when a string is passed as an argument.
A live demo at jsFiddle. This fiddle is just an example to show how the code works in a single document.

Categories

Resources