为什么这告诉我我的变量未定义?

时间:2019-03-24 02:00:35

标签: javascript

我想创建一个警报,以强制用户在提交之前在输入表单中输入大于0的值。

为什么告诉我我的var未定义?

function rollDice(bet) {
  bet = document.getElementsByName("startingBet").value;
  if (bet <= 0) {
    alert("You must place a bet");
    return false;
  }
}
<form action="luckysevens.html" onsubmit="rollDice()">
  <p>Starting Bet: $ <input type="number" name="startingBet" id="startingBet" /></p>
  <input type="submit" name="play" value="Play" />
</form>

3 个答案:

答案 0 :(得分:2)

函数中的

bet需要在其中包含一个var。 rollDice()中没有参数传递给onsubmit()。另外,请使用let代替var。这是JavaScript中的letvar之间的区别。

您在这里:

function rollDice() {
  let bet = document.getElementsById("startingBet").value;
  if (bet <= 0) {
    alert("You must place a bet");
    return false;
  }
}
<form action="" onsubmit="rollDice()">
  <p>Starting Bet: $ <input type="number" name="startingBet" id="startingBet" /></p>
  <input type="submit" name="play" value="Play" />
</form>

希望这会有所帮助,

答案 1 :(得分:2)

由于分配了投注值,所以我看不到未定义投注的原因。但是很明显,由于您使用undefined,所以下注的值是getElementsByName,它将具有类似数组的值,您不能直接从中获取值。您需要遍历它。为简单起见,您可以使用getElementsByName("startingBet")[0]。但我建议您执行以下操作。

替换此:

document.getElementsByName("startingBet").value;

与此:

document.getElementById("startingBet").value;

答案 2 :(得分:1)

function validateInstCity($inst_province = null, $inst_city = null) { if (empty($inst_province) || empty($inst_city)) { } $idx; for ($i=0; $i < count($states_json); $i++) { if ($states_json[$i]['sigla'] == $inst_province) { $idx = $i; break; } } $cities= array(); for ($i=0; $i < count($states_json[$idx]['cidades']); $i++) { array_push($cities, $states_json[$idx]['cidades'][$i]); } if (in_array($inst_city, $cities, false)) { return true; } else { return false; } } 返回一个getElementsByName

HTMLCollection
function rollDice(bet) {
    // assuming funciton parameter as an optional
    const _bet = +(bet || document.getElementsByName("startingBet")[0].value);
    
    // with query selector
    // document.querySelector('[name="startingBet"]').value
    
    // with id selector
    // document.getElementById("startingBet").value;

    if (!_bet) {
        alert("You must place a bet");
        return false;
    }
 }

相关问题