javascripthtmlhandlebars.jsexpress-handlebarshandlebarshelper

How to have an addEventListener click conditional work with radio buttons in hbs


This hbs file only calls from js file in the else conditional and never calls from the js file in the if conditional. The desired result is so that if the male radio button is checked, a male name is generated when the button is clicked, and a female name is generated when the button is clicked otherwise.

Section of relevant Handlebars file:

<body>
    <div class ="container">
        <h1> Random Name Generator</h1>
        <div class="result"></div>
        <form id="genders">
        <input type="radio" id="isMale" name="gender" checked>Male</input>
        <input type="radio" id="isFemale" name="gender">Female</input>
        </form>
        <button class="btn btn-primary" id="generate">Generate Name</button>
    </div>
    <script src="./app.js"></script>
    <script src="./app2.js"></script>
    <script>
        const resultDiv = document.querySelector('.result');
        const generateBtn = document.querySelector('#generate');
        generateBtn.addEventListener('click', () => {
      {{#if isMale}}
            loadRandomMaleName(resultDiv);  
        {{else}}
            loadRandomFemaleName(resultDiv);
        {{/if}}
        });
        </script>
</body>

JavaScript file for if conditional:

const loadRandomMaleName = (resultDiv) => {
    fetch('http://localhost:3000/random-name')
    .then(response => response.json())
    .then(result => {
        resultDiv.classList.add('alert', 'alert-success');
        resultDiv.innerHTML = `<h2>${result.male_first_name} ${result.last_name}</h2>`;
    });
}

JavaScript file for else conditional:

const loadRandomFemaleName = (resultDiv) => {
    fetch('http://localhost:3000/random-name')
    .then(response => response.json())
    .then(result => {
        resultDiv.classList.add('alert', 'alert-success');
        resultDiv.innerHTML = `<h2>${result.female_first_name} ${result.last_name}</h2>`;
    });
}

Solution

  • I believe your problem is that the handlebarsjs is evaluated before it is served to the user. So when the use interacts with the page only the else option is there. What you should probably do is have an if/else using JS based on the value of the ratio button.

    How to get the selected radio button’s value?