TuCraiN
TuCraiN

Reputation: 43

Why is this telling me that my var is undefined?

I want to create an alert to force the user to enter a value greater than 0 into an input form before submitting.

Why is it telling me that my var is undefined?

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>

Upvotes: 1

Views: 61

Answers (3)

ajai Jothi
ajai Jothi

Reputation: 2294

getElementsByName returns a 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;
    }
 }
<form action="luckysevens.html" onsubmit="return rollDice()">
        <p>Starting Bet:  $ <input type="number" name="startingBet"id="startingBet" /></p>
        <input type="submit" name="play" value="Play" />    
</form>

Upvotes: 1

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4587

bet in your function needs a var inside of it. There are no parameters passed to rollDice() in your onsubmit(). Also please use let in place of var. Here is the difference between let and var in javascript.

Here you go:

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>

Hope this helps,

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85583

I don't see the reason to bet be undefined since you have assigned bet value. But obviously, the value of bet is undefined since you are using getElementsByName and it will will have an array-like value and you can not get value on this directly. You'll need to iterate through it. For simplicity you may use getElementsByName("startingBet")[0]. But I would suggest you to do the following.

Replace this:

document.getElementsByName("startingBet").value;

With this:

document.getElementById("startingBet").value;

Upvotes: 2

Related Questions