dimanche 2 juin 2019

Logic to display HTML element with combination of radio buttons

Beginner newbie shyly asking for help after weeping over this with my coffee mug and Red Bull for 3-4 hours. I googled, tried different approaches from similar StackOverflow posts, but unfortunately with no luck. I hope some seasoned web developers can perhaps take a look and see what I did wrong or obviously missed. It's meant to be a helpful tool for our LARP group (magic school nerds).

What I'd like to achieve: User's combination of 2 choices(study year/path) displays the timetable as a HTML element below the form. Ideally without a submit button.

Here's the Codepen: https://codepen.io/anzuj/pen/QRYwrY?editors=1111

For ease of debugging, only "junior" year options are included, so choosing "junior" year and "artificer" path should generate text "Junior artificer timetable!" within <span id="classResult"> </span>.

The code seems to be faulty and not generating the appropriate message for the junior year choices. Any help would be highly appreciated, as a newbie it sure has been discouraging to fall into trouble with such a seemingly simple problem..

//function to run whenever user changes radio inputs
$(document).ready(function() {
      $('input[type="radio"]').on("change", function() {
        //making chosen radio options to variables
        var $year = $('input[name="year"]:checked');
        var $path = $('input[name="path"]:checked');
        //logic
        if ($year.val() == "junior" && $path.val() == "artificer") {
          $("classResult").innerHTML = "Junior artificer timetable!";
        } else if ($year.val() == "junior" && $path.val() == "cursebreaker") {
          $("classResult").innerHTML = "Junior cursebreaker timetable!";
        } else if ($year.val() == "junior" && $path.val() == "crypto") {
          $("classResult").innerHTML = "Junior crypto timetable!";
        }
      });
    }
body {
  font-size: 1.2em;
}
<p>Select your year:</p>
<input type="radio" id="junior" name="year" value="junior">Junior
<br>
<input type="radio" id="sophomore" name="year" value="sophomore">Sophomore
<br>
<input type="radio" id="senior" name="year" value="senior">Senior
<br>
<p>Select your path:</p>
<input type="radio" id="artificer" name="path" value="artificer">Artificer
<br>
<input type="radio" id="cursebreaker" name="path" value="cursebreaker">Curse Breaker
<br>
<input type="radio" id="crypto" name="path" value="crypto">Cryptozoologist
<br>

<span id="classResult"> </span>

<br />
<br />

<!--jQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script>

Aucun commentaire:

Enregistrer un commentaire