Use Jquery to get value

I am making a quiz app. The console isn't running in my code, so I know that the jQuery is wrong in some way. I want to get the value so that I can compare it to the answer.

$('.quizAnswers').on('submit', '.choice', function(event) {
  event.preventDefault();

  let playerAnswer = $(this).value();
  console.log(playerAnswer + " clicked");

  $(this).closest('.quizQuestion').remove();
  recieveAnswer(playerAnswer);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quizQuestion quizSlide">
  <form class="quizAnswers">
    <input type="button" value="A" class="choice"></input>
    <input type="button" value="B" class="choice"></input>
    <input type="button" value="C" class="choice"></input>
    <input type="button" value="D" class="choice"></input>
  </form>

Upvotes: 1

Views: 63

Answers (2)

Quentin
Quentin

Reputation: 943142

The JS runs when you get a submit event on a button, but:

  • Only forms have submit events
  • Nothing will ever submit the form because you have you have type="button" which is a button that does nothing by default.

So:

Your next problem is $(this).value();: The method is called val not value

$('.quizAnswers').on('click', '.choice', function(event) {
  event.preventDefault();
  let playerAnswer = $(this).val();
  console.log(playerAnswer + " clicked");
  $(this).closest('.quizQuestion').remove();
  //  recieveAnswer(playerAnswer);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class='quizAnswers'>
  <input type='submit' value='A' class='choice'>
  <input type='submit' value='B' class='choice'>
  <input type='submit' value='C' class='choice'>
  <input type='submit' value='D' class='choice'>
</form>

Upvotes: 3

Sarfraaz
Sarfraaz

Reputation: 1269

I think what you mean to use here is radio buttons

You can give same name for all radio button inputs & get the value of selected radio on form submit like this

$('#quizAnswers').on('submit', function(event){

      event.preventDefault();
      
       var answer = $('input[name=choice]:checked', '#quizAnswers').val();
      
      console.log(answer+' is selected');
      
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='quizQuestion quizSlide'>
<form id='quizAnswers'> 
  <input type='radio' value='A' name='choice'/> A
  <input type='radio' value='B' name='choice'/> B
  <input type='radio' value='C' name='choice'/> C
  <input type='radio' value='D' name='choice'/> D
  <button type="submit">Submit</button>
</form>
</div>

Upvotes: 2

Related Questions