Home > database >  JavaScript get value from focus button
JavaScript get value from focus button

Time:12-18

I'm using pure JavaScript to create a game. In the game, the user can choose from three weapons, which are three buttons. The last clicked 'weapon' button will have the focus status (so I could get weaponbutton.value). Then, the user presses the 'start' button to start the game.

But when the 'start' button is pressed, the focus status automatically changed to the 'start' button. I couldn't get the weaponbutton.value. So how can I get the weaponbutton.value? Thank you very much. My code is below:

const weapon1 = document.getElementById("weapon1");
const weapon2 = document.getElementById("weapon2");
const weapon3 = document.getElementById("weapon3");
var playerATT = 10;
var weaponValue;

if(weapon1.focus() === true){
    weaponValue = 3;
}
else if(weapon2.focus() === true) {
    weaponValue = 6;
}
else if(weapon3.focus() === true) {
    weaponValue = 9;
}

StartButton.onclick = function(){
    playerATT = playerATT   weaponValue;

}

seeking out ways to get the weaponbutton.value, then pass the value to the startButton.

CodePudding user response:

const weapon1 = document.getElementById("weapon1");
const weapon2 = document.getElementById("weapon2");
const weapon3 = document.getElementById("weapon3");
var weaponValue;

document.getElementById('start').addEventListener('click', function(){
    console.log('weapon value', weaponValue)
})

// I'd use "click" instead of "focus", but I don't know if that's something particular to your game.
weapon1.addEventListener('focus', () => { weaponValue = 3 })
weapon2.addEventListener('focus', () => { weaponValue = 6 })
weapon3.addEventListener('focus', () => { weaponValue = 9 })
<button id="weapon1" type="button">Weapon 1</button>
<button id="weapon2" type="button">Weapon 2</button>
<button id="weapon3" type="button">Weapon 3</button>

<button id="start" type="button">Start</button>

CodePudding user response:

That's not what focus does — focus focuses an element, and returns undefined. You're probably mixing it up with the focus event. Instead what would make sense is setting a variable based on which button is clicked.

const weapon1 = document.getElementById('weapon1')
const weapon2 = document.getElementById('weapon2')
const weapon3 = document.getElementById('weapon3')
let playerATT = 10
let weaponValue = 3

weapon1.onclick = () => { weaponValue = 3 }
weapon2.onclick = () => { weaponValue = 6 }
weapon3.onclick = () => { weaponValue = 9 }

StartButton.onclick = () => { playerATT  = weaponValue }
  • Related