Matt Picca Matt Picca - 2 months ago 8
HTML Question

Basic javascript user-input changing div

I'm trying to change the width of a box using user-input with a for loop and if-else statement. Cant seem to get the first if statement to execute. Here is the javascript:

function changeWidth(){
var widthSize = document.getElementById("num").value;
for(var s = 0; s < widthSize; s++){
if(s < 0 || s > 800){
alert("Not a valid width size"); }
else {
document.getElementById("box-1").style.width="s";
}
}
}


The CSS:

.box {
border: 1px solid black;
width: 200px;
height: 200px;
float:left;
margin-left:30px;
}


The HTML:

<input type="number" id="num" name="num" value="" placeholder="Please enter width size" />
<input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" />
<div class="box" id="box-1"></div>

Answer

You don't need a loop, this should do it.

function changeWidth(){
    var widthSize=document.getElementById("num").value;
    if(widthSize < 0 || widthSize > 800){
        alert("Not a valid width size"); }
    else {
        document.getElementById("box-1").style.width=widthSize+"px";
    }
}
Comments