0

I have a speed typing game. I also have a form with 3 radio buttons and i want to select the level of the game based on the selected radio button. How can i do that?

I've tried with document.querySelector('input[name="genderS"]:checked').value; this code here. But it doesn't worked

const levels = {
  easy: 5,
  medium: 3,
  hard: 1
};


let easyChecked = document.querySelector('#radio-easy').checked;
let mediumChecked = document.querySelector('#radio-medium').checked;
let hardChecked = document.querySelector('#radio-hard').checked;

var currentLevel = levels.medium;
let time = currentLevel;
let score = 0;
let isPlaying;

// To change level
function isChecked() {

}

I expect currentLevel variable to be changed based on the radio buttons.

  • 2
    You;ll need to post your HTML etc so people can help – Matthew Page Feb 17 '19 at 13:22
  • Did you read this:? https://stackoverflow.com/questions/1423777/how-can-i-check-whether-a-radio-button-is-selected-with-javascript/1423852 – Ele Feb 17 '19 at 13:24
  • I think your issue is that this code is running once at the beginning and then your checking the radio buttons and it's not updating like your expecting. For that you will need to listen for the event change. – cmac Feb 17 '19 at 13:26

2 Answers2

0

Something like this:

 var currentLevel = null;  // not set yet

 let easyChecked = document.querySelector('#radio-easy');
 let mediumChecked = document.querySelector('#radio-medium');
 let hardChecked = document.querySelector('#radio-hard');

 easyChecked.addEventListener("change", function() {
   currentLevel = this.checked; // update currentLevel on change
 }); 
 mediumChecked.addEventListener("change", function() {
   currentLevel = this.checked; // update currentLevel on change
 }); 
 hardChecked.addEventListener("change", function() {
   hardChecked = this.checked; // update currentLevel on change
 }); 

Now currentLevel will be updated when the radio buttons change.

Jamie Barker
  • 8,145
  • 3
  • 29
  • 64
cmac
  • 3,123
  • 6
  • 36
  • 49
0

Simply, make your radio button HTML code with the same name like this:

<input type="radio" name="level" value="easy"> Easy<br>
<input type="radio" name="level" value="medium"> Medium<br>
<input type="radio" name="level" value="hard"> Hard<br>

then bind all radio button with on change event by foreach loop

let selectedLevel;
const levelButtons = document.querySelectorAll('input[name="level"]');
Array.prototype.forEach.call(levelButtons, function(btn) {
  btn.addEventListener('change', function(){
    selectedLevel = this.value;
    console.log(selectedLevel);
  });
});