简体   繁体   中英

in Javascript, how can I make input boxes that changes as the values inside them change?

I know I might not be explaining myself very well but here is the code. I am experimenting with javascript by making a program that calculates square feet.

JS, in head

function myFunction()
{
    var x =0;
    var y =0;
    var z =0;

    x =document.getElementById("sqrft");
    y = document.getElementById("length");
    z = document.getElementById("width");
    if(x>0 && y>0)
    {
        x.value=y*z;
    }
}

HTML

<p>A function is triggered when the user releases a key in the input field. The function transforms the character to upper case.</p>
Enter your length: <input type="text" id="length" onkeyup="myFunction()">
Enter your width: <input type="text" id="width" onkeyup="myFunction()">
Enter your totalsqrft: <input type="text" id="sqrft" onkeyup="x.value">

So basically I am trying to make the value of "sqrft" change live as the value of length and width changes.

You need to use:

function myFunction() {
    var x = 0;
    var y = 0;
    var z = 0;

    x = document.getElementById("sqrft"); 
    y = document.getElementById("length").value; // get value of y
    z = document.getElementById("width").value;// get value of z
    if (y > 0 && z > 0) { // compare value of y and z instead of x and y
        x.value = y * z;
    }
}

Fiddle Demo

function myFunction() {
  var width = +document.getElementById("width").value;
  var height =+document.getElementById("length").value;    
    if (width > 0 && height > 0) { 
        var area = width * height;
  document.getElementById("sqrft").value = area;
    }
}

DEMO

x.value=y.value *z.value;

You're just getting a reference to the y and z elements. Not their value.

You should probably also do some checks to ensure that you're getting a number back first as well in case users enter text you don't expect

My suggestion is event-delegation : you use an enclosing div and put a listener on the change event (simplified HTML):

<div id="calc">
    <input name="height" id="height"/><label for="height">height</label>
    <input name="width" id="width"/><label for="height">width</label>
</div>
<div id="result"></div>


document.querySelector("#calc").addEventListener("change", function(){
    document.querySelector("#result").textContent="result: "+document.querySelector("#height").value*1*document.querySelector("#width").value*1
});

This is a quite hacky solution, but should show you the way. The JSFiddle to play with is here

Read the MDN -article about querySelector for explanation and compatibility questions.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM