kaki55
kaki55

Reputation: 19

Not getting the value of Radio input Javascript

am not able to get the values of radio button input

let movieValue = document.querySelectorAll('input[type="radio"]');
movieValue.forEach(radio => {
  if (radio.checked) {
    console.log(radio.value)
  }
});
<label for="movie-list" class="pick-movie">Please Select the Movie:</label>
<br>
<div class="movies">
  <input type="radio" value="18" class="moves" name="movie-list"> Fast and Furious-9- 18 USD</input>
  <br>
  <input type="radio" value="14" class="moves" name="movie-list"> Joker - 14 USD</input>
  <br>
  <input type="radio" value="15" class="moves" name="movie-list"> Spider-Man -15 USD</input>
</div>
<br>

when i did this....nothing is displaying on console...just blank...

Upvotes: 1

Views: 72

Answers (2)

Always Helping
Always Helping

Reputation: 14570

You need to use addeventListener to check for radio value when you click on that radio button.

You were just using forEach function which will not check for checked value because you do not have any checked attr applied to any of the radio buttons you have.

So you need to use addeventListener with a change event to see where you have clicked at to display its value.

Also, you do not need to use this => </input> to close an input element you can just use />

Live Demo:

let movieValue = document.querySelectorAll('input[type="radio"]');
movieValue.forEach(radio => {
  radio.addEventListener('change', function() {
    if (radio.checked) {
      console.log(radio.value + " : " + radio.nextElementSibling.innerText)
    }
  }, false);
});
<label for="movie-list" class="pick-movie">Please Select the Movie:</label>
<br>
<div class="movies">
  <input type="radio" value="18" id="movie1" class="moves" name="movie-list">
  <label for="movie1"> Fast and Furious-9- 18 USD </label>
  <br>
  <input type="radio" value="14" id="movie2" class="moves" name="movie-list">
  <label for="movie2"> Joker - 14 USD</label>
  <br>
  <input type="radio" value="15" id="movie3" class="moves" name="movie-list">
  <label for="movie3"> Spider-Man -15 USD</label>
</div>
<br>

Upvotes: 3

Asutosh
Asutosh

Reputation: 1828

window.addEventListener('load', function() {

  let movieValue = document.querySelectorAll('input[type="radio"]');

  movieValue.forEach((movie) => {
    movie.addEventListener('change', function() {
      if (movie.checked) {
        console.log(movie.value);
      }

    });

  })


});
<label for="movie-list" class="pick-movie">Please Select the Movie:</label>
<br>
<div class="movies">
  <input type="radio" value="18" class="moves" name="movie-list"> Fast and Furious-9- 18 USD</input>
  <br>
  <input type="radio" value="14" class="moves" name="movie-list"> Joker - 14 USD</input>
  <br>
  <input type="radio" value="15" class="moves" name="movie-list"> Spider-Man -15 USD</input>
</div>
<br>

Upvotes: -1

Related Questions