I am attempting to create a square from user inputs.
I thought that having having the height and width in my style multiplied together would create the square after clicking my button.
My question is: How do I get the user inputs to be used for the height and width of the box?
HTML:
<input type="text" id="width">
<input type="text" id="height">
<button onclick="calculate()">Click Me For Square</button>
<br>
<p id="box"></p>
Javascript:
function calculate() {
var w = document.getElementById("width").value;
var h = document.getElementById("height").value;
box = document.getElementById("box");
box.innerHTML = " " + (w*h);
}
var square = document.createElement('div');
square.className = 'square';
document.body.appendChild(square);
Style
background: red;
width: (h*w);
height: (w*h);
margin: 50px auto;
}
set square.style.width/height
with the input values like below demo:
function calculate() { var w = document.getElementById("width").value; var h = document.getElementById("height").value; box = document.getElementById("box"); box.innerHTML = " " + (w*h); document.querySelectorAll('div.square').forEach(item => item.remove()) var square = document.createElement('div'); square.className = 'square'; square.style.width = w + 'px' // width square.style.height = h + 'px' // height document.body.appendChild(square); }
.square { background: red; }
<input type="text" id="width" value="25"> <input type="text" id="height" value="25"> <button onclick="calculate()">Click Me For Square</button> <br> <p id="box"></p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.