Ternary condition in javascript is not selecting button radio

I am trying to use the ternary operator like this in button radio in javascript:

$(document).on('click', '.limp-orc1', function(){
   var empl_id = $(this).parents("tr").attr("id");  

$.getJSON('./historicoaval?empl_id' + '&empl_id=' + empl_id, function (data) {
                 for (var i = 0; i < data.length; i++) {  

                Id = data[i][0];
                Utente = data[i][1];
                Data = data[i][2];
                radio = data[i][3];
        
         }  

             var linha = ``;

            linha += `<li>
        <label for="radio" style="font-size: 12px;">Descola-se</label>
        <ul class="flex-outer">

                <div class="subscription-container">
                  <input type="radio" ${radio} == 1 ? 'checked' : ''>
                  <label class="subscription__button">
                      <h3 class="subscription__title">Autónomo (Sim)</h3>

                  </label>

                  <input type="radio" ${radio} == 2 ? 'checked' : ''>
                  <label class="subscription__button">
                      <h3 class="subscription__title">Necessita de apoio pontual</h3>

                  </label>
                  
                  <input type="radio" ${radio} == 3 ? 'checked' : ''>
                  <label class="subscription__button">
                      <h3 class="subscription__title">Necessita sempre de apoio</h3>
                  </label>
                  
                  <input type="radio" ${radio} == 4 ? 'checked' : ''>
                  <label class="subscription__button">
                      <h3 class="subscription__title">Não Autónomo (Não)</h3>
                  </label>
                  
                  <input type="radio" ${radio} == 5 ? 'checked' : ''>
                  <label class="subscription__button">
                      <h3 class="subscription__title">Não aplicável</h3>
                  </label>
                </div>
            
        </ul>
        </li>`;

But it is not working. Do not select any of the buttons.

What could I be doing wrong to not work?

Can they help to solve this problem?

Answer

<input type="radio" ${radio} == 3 ? 'checked' : ''> is incorrect. This will evaluate to:

<input type="radio" true == 3 ? 'checked' : ''>

Which is not valid HTML.

Instead, you should do the following:

<input type="radio" ${radio === 3 ? 'checked' : ''}>

If the condition is true, this will become <input type="radio" checked>, otherwise just <input type="radio" />

Leave a Reply

Your email address will not be published. Required fields are marked *