如何使用value属性在2个文本框中显示2个以上的值

时间:2016-07-07 18:59:04

标签: javascript

我无法在两个不同的禁用输入文本框中显示答案。我不确定这是我的if语句还是我的函数调用。我在else语句中调用它,以便在禁用的输入中显示它。

<head>
    <script>
    "use strict";
    var $ = function(id) {
        return document.getElementById(id);
    };


    //make change
    var makeChange = function(quarters, dimes) {
        var quarter_value = 25;
        var dime_value = 10;

        var cents = parseInt($("cents").value);
        if (quarter_value <= cents){
            var quarters = parseInt(cents / quarter_value);
            var changeValue = parseInt(quarters - cents);
            return quarters;
        }
        if (dime_value <= changeValue) {
            var dimes = parseInt(changeValue / dime_value);
            return dimes;
        }
    };

    //validate entry 0-99
    var processEntries = function() {

        var cents = parseInt($("cents").value);

        if ( isNaN(cents) || cents < 0 || cents > 99) {
            alert("Must be a number 0 - 99");
        }
        else {
            $("quarters").value = makeChange(quarters, dimes);
            $("dimes").value = makeChange(quarters, dimes);
        }
    };

    window.onload = function() {
        $("calculate").onclick = processEntries;
    };
    </script>
</head>

<body>
    <main>
    <h1>Change Calculator</h1>

    <label>Enter amount of change due (0-99):</label>
    <input type="text" id="cents" />

    <input type="button" value="Calculate" name="calculate" id="calculate" /><br><br>

    <label for="quarters">Quarters:</label>
    <input type="text" id="quarters" disabled><br>

    <label for="dimes">Dimes:</label>
    <input type="text" id="dimes" disabled><br>

    <label for="nickels">Nickels:</label>
    <input type="text" id="nickels" disabled><br>

    <label for="pennies">Pennies:</label>
    <input type="text" id="pennies" disabled><br>

    </main>
</body>
</html>

4 个答案:

答案 0 :(得分:0)

这是一种方法。如果你想使用makeChange()函数,请告诉我。

document.getElementById("calculate").addEventListener("click", function(){
  var total = parseInt(document.getElementById("cents").value);
  if(total !== total) { return;}

  var quarters = Math.floor(total / 25);
  total -= quarters * 25;

  var dimes = Math.floor(total / 10);
  total -= dimes * 10;

  var nickels = Math.floor(total / 5);
  total -= nickels * 5;

  var pennies = total;
  total -= pennies;

  document.getElementById("quarters").value= quarters;
  document.getElementById("dimes").value= dimes;
  document.getElementById("nickels").value= nickels;
  document.getElementById("pennies").value= pennies;
});
<h1>Change Calculator</h1>
<div>
  <label>Enter amount of change due (0-99):</label>
  <input type="text" id="cents" />
</div>

<div style="margin-bottom: 1em;">
  <input type="button" value="Calculate" name="calculate" id="calculate" />
</div>

<div>
  <label for="quarters">Quarters:</label>
  <input type="text" id="quarters" disabled="disabled" />
</div>

<div>
  <label for="dimes">Dimes:</label>
  <input type="text" id="dimes" disabled="disabled" />
</div>

<div>
  <label for="nickels">Nickels:</label>
  <input type="text" id="nickels" disabled="disabled" />
</div>

<div>
  <label for="pennies">Pennies:</label>
  <input type="text" id="pennies" disabled="disabled" />
</div>

答案 1 :(得分:0)

您在此处有错误:

var cents = parseInt($("cents").value);

&#34;仙&#34;不是标签名称,它是一个id:

var cents = parseInt($("#cents").value);

同样在这里

$("quarters").value = makeChange(quarters, dimes);
$("dimes").value = makeChange(quarters, dimes);

应该是

$("#quarters").value = makeChange(quarters, dimes);
$("#dimes").value = makeChange(quarters, dimes);

希望这能解决您的问题。

答案 2 :(得分:0)

我注意到可以重新定义的地方,尽可能地注释了你的代码。最大的问题是makeChange()。如果你有办法通过输入更新运行总计&#34;美分&#34;那么你的大部分代码都会有效。基本上,变量changeValue可能已用于更新输入,然后角钱将像季度一样工作。我并不热衷于这种方法,我希望我的注释能指出你更好的方向

&#13;
&#13;
// ---------------------------
// $() shall be sugar for document.getElementById()
// Note: could be a little confusing as some might expect $() to
// be a jQuery result.
// ---------------------------
var $ = function(id) { return document.getElementById(id); };
// ---------------------------

// ---------------------------
// Validate entry 0-99
// ---------------------------
var processEntries = function() {
  var cents = parseInt( $("cents").value );
  
  // ---------------------------
  // Let's set some denominations so it is harder to mess things up.
  // You did somehting similar in makeChange()
  // ---------------------------
  var denom = {
    quarter : 25,
    dime: 10,
    nickel : 5,
    penny : 1
  };
  // ---------------------------
  
  
    if ( isNaN(cents) || cents < 0 || cents > 99){
      alert("Must be a number 0 - 99");

      // ---------------------------
      // At this point we can abort.
      // Rather than an "if else" you might just have this "if" ending
      // in a "return"
      // ---------------------------
    }   
    else {
      // ---------------------------
      // Our amount is good, so lets calculate the change.
      // ---------------------------

      // ---------------------------
      // We want to update the input "quarters" with the number of quarters
      // in the change by calling the makeChange() function.
      //
      // Note, the variable quarters and $("quarters") are actually the same
      // thing. This may or may not be what you are expecting.
      //
      // The variable quarters is being created automatically by the browser
      // because there is an element with that id.  You should probably not
      // rely on this fact. If you intended to pass in the element quarters
      // into your makeChange() then you probably want to do so more explicitely
      // as $("quarters") or define a new variable
      //
      // var quarters = $("quarters");
      //
      // At this point it might be valuable to think about what makeChange()
      // is/should be doing.  It looks like you don't want makeChange() to both
      // calculate the change AND update your GUI. I think that is a good
      // separation.  If that is the case, then what makeChange() really needs to
      // know is what the outstanding amount is.
      //
      // The next question might be is makeChange() called once like
      // makeChange(98) and returns an object or array of the number of each coins
      // or is makeChange() called once for each type of coin returning just the
      // number of that coin.  It looks like you are after the latter and that is
      // fine though it also means we need to track the total in the main code.
      //
      // So, if the above is correct, then we probably want makeChange() to have
      // a slightly different signature.  I'll call a new function makeChange2()
      // with this proposal. makeChange2(outstandingBallance, coinDenomination)
      // and we will expect it to return an integer.
      // ---------------------------

      // ---------------------------
      // $("quarters").value = makeChange(quarters, dimes);
      var quartersReturned = makeChange2(cents, denom.quarter);
      cents = cents - quartersReturned * denom.quarter;
      $("quarters").value = quartersReturned;
      // ---------------------------

      // ---------------------------
      // $("dimes").value = makeChange(quarters, dimes);
      var dimesReturned = makeChange2(cents, denom.dime);
      cents = cents - dimesReturned * denom.dime;
      $("dimes").value = dimesReturned;
      // ---------------------------

      // ---------------------------
      var nickelsReturned = makeChange2(cents, denom.nickel);
      cents = cents - nickelsReturned * denom.nickel;
      $("nickels").value = nickelsReturned;
      // ---------------------------

      // ---------------------------
      var penniesReturned = makeChange2(cents, denom.penny);
      cents = cents - penniesReturned * denom.penny;
      $("pennies").value = penniesReturned;
      // ---------------------------
      
      // ---------------------------
    }
};
// ---------------------------

// ---------------------------
// makeChange2()
// Given a total and a denomination return the maximum number of coins.
// ---------------------------
function makeChange2(outstandingBallance, coinDenomination) {
  return Math.floor(outstandingBallance / coinDenomination);
}
// ---------------------------

// ---------------------------
// makeChange()
// No longer called, but let's take a look at it.
// We pass in some GUI elements and return something... looks like an integer
// ---------------------------
var makeChange = function(quarters, dimes){
  // ---------------------------
  // Set some standard denominations.  Looks good.  We now do something similar
  // outside this function.
  // ---------------------------
  var quarter_value = 25;
  var dime_value = 10;
  // ---------------------------

  // ---------------------------
  // Get the outstanding amount.  Looks good, again we get this outside this scope now 
  // ---------------------------
  var cents = parseInt($("cents").value);
  // ---------------------------

  // ---------------------------
  // If the outstanding acount is more than a quarter, then return some number of quarters
  // ---------------------------
  if (quarter_value <= cents){
    // ---------------------------
    // Careful here, you just changed what quarters means.
    // You might also want to use Math.floor() to be more explicite.
    // ---------------------------
    var quarters = parseInt(cents / quarter_value);
    // ---------------------------

    // ---------------------------
    // It looks like you want to potentiall calculate the value of the change
    // about to be given, but remember quarters in now the number of quarters
    // to potentially give so (quarters - cents) is probably not what you wanted here.
    // maybe more like:
    //
    // var changeValue = quarters * quarter_value;
    // or
    // var changeValue = cents - quarters * quarter_value;
    //
    // having done that though, you would still likely want to do "something" with changeValue
    // ---------------------------
    var changeValue = parseInt(quarters - cents);
    // ---------------------------

    // ---------------------------
    // return the number of quarters to be given
    // ---------------------------
    return quarters;
    // ---------------------------
  }
  // ---------------------------

  // ---------------------------
  // You might have wanted to do something similar to what you did with quarters here.
  // See notes above.
  //
  // BUT, changeValue likely never gets set correctly.
  // it exists (thanks to hoisting) but is undefined if there are no quarters.
  // If there are quarters then we already exitted above.
  //
  // Assuming you wanted to call this function multiple times, changeValue would have had to
  // update $("cents").value with the running total and that is probably not a great idea.
  // If you did, then the variable cents could have been used here rather than changeValue.
  // ---------------------------
  if (dime_value <= changeValue){
    var dimes = parseInt(changeValue / dime_value);
    return dimes;
  }
  // ---------------------------

};
// ---------------------------

window.onload = function() { $("calculate").onclick = processEntries; };
&#13;
<h1>Change Calculator</h1>

<label>Enter amount of change due (0-99):</label>
<input type="text" id="cents" />

<input type="button" value="Calculate" name="calculate" id="calculate" /><br><br>

<label for="quarters">Quarters:</label>
<input type="text" id="quarters" disabled><br>

<label for="dimes">Dimes:</label>
<input type="text" id="dimes" disabled><br>

<label for="nickels">Nickels:</label>
<input type="text" id="nickels" disabled><br>

<label for="pennies">Pennies:</label>
<input type="text" id="pennies" disabled><br>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

makeChange函数有很多问题,所以我只关注它。

//make change
var makeChange = function(quarters, dimes) {
    var quarter_value = 25;
    var dime_value = 10;

    var cents = parseInt($("cents").value);
    if (quarter_value <= cents){
        var quarters = parseInt(cents / quarter_value);
        var changeValue = parseInt(quarters - cents);
        return quarters;
    }
    if (dime_value <= changeValue) {
        var dimes = parseInt(changeValue / dime_value);
        return dimes;
    }
};

该函数正在使用参数quartersdimes,但随后您声明了局部变量var quarters = parseInt(cents / quarter_value);,因此局部变量会隐藏参数。

即使您没有重新声明它们,为参数分配值也不会更改传递给函数的值 - javascript按值传递,而不是通过引用传递。

您设置了var changeValue = parseInt(quarters - cents);,然后在dime_value比较中使用changeValue。这是有效的,因为在javascript var声明被提升到函数的顶部,所以你实际拥有的是:

var makeChange = function(quarters, dimes) {
    var quarter_value = 25;
    var dime_value = 10;
    var changeValue;

    var cents = parse.....

请注意,在大多数其他语言中,这不起作用,因为changeValue只存在于声明它的if块中,并且将不再存在于if (dime_value < changeValue)语句中。

使用parseInt(cents / quarter_value)有效,只获取除法的整数部分,例如parseInt(71/25)产生2,但令人困惑 - Math.trunc(cents / quarter_value)显示你做得更好......除去然后截断结果。

函数makeChange也知道输入字段cents。当你打电话两次时:

$("quarters").value = makeChange(quarters, dimes);
$("dimes").value = makeChange(quarters, dimes);

...每次获取在美分字段中输入的值时,每次进行四分之一计算并返回时,除非分数&lt;然后它将进行角钱计算并返回 。在任何一种情况下,四分之一角钱参数的值都不会像我之前提到的那样改变

由于您无法通过参数返回值,因此最好将单个数字参数cents传递给makeChange = function(cents)并返回包含四分之一的对象,硬币,镍币和硬币。

var makeChange = function(cents) {
    var quarter_val = 25;
    var dime_val    = 10;
    var nickel_val  =  5;

    var coins = {
            'quarters' : 0,
            'dimes'    : 0,
            'nickels'  : 0,
            'pennies'  : 0
        };

    var remaining = cents; // how much of the original cents value remains

    // Figure out how many quarters. Don't have to test if (quarter_val < cents) first
    // because .trunc() of a fraction will produce 0 quarters
    // e.g. 10 / 25 == 0.4 and Math.trunc(0.4) is 0
    coins.quarters = Math.trunc(remaining / quarter_val);
    // Reduce the remaining amount by the value of the quarters.
    remaining = remaining - (coins.quarters * quarter_val);

    // Now do the same for dimes and nickels, and what is left then is pennies
    coins.dimes = Math.trunc(remaining / dime_val);
    remaining = remaining - (coins.dimes * dime_val);

    coins.nickels = Math.trunc(remaining / nickel_val);
    remaining = remaining - (coins.nickels * nickel_val);

    coins.pennies = remaining;

    return coins;
};

现在调用它就像

var change = makeChange( parseInt($("cents").value) );
$("quarters").value = change.quarters;
$("dimes").value = change.dimes;
// ...etc...