Search code examples
javascripthtmlradio-button

if I select No in radio button, it just showing Blank


There are 4 Yes,No radio buttons and if I choose Yes, it shows the value 'YES'. But, if I chooseNo, it just showing blank. May I know how can I fix it?

<div id='testtwo' style="display:block;">
  <label class="control-label col-sm-4" for="pnl">Is the packing properly vacuum sealed? :</label>
  <div class="col-sm-4" style="margin-top:19px;">
    <p class="form-control-static" style="margin-top: -7px;display: inline-flex;color: darkslategrey;">
        <input type="radio" name="pkyes" value="YES">
          <label for="pkyes" style="margin-left: 6px; margin-top: 8px;">YES</label><br>
          
        <input type="radio" name="pkyes" value="NO" style="margin-left: 16px;">
          <label for="pkno" style="margin-left: 6px; margin-top: 8px;">NO</label><br>  
    </p>
  </div></div>

Below is JavaScript.

    var testasd=document.querySelector('input[type=radio][name=pkyes]');        
if(testasd.checked == false ){
    var pk = '';
}else {
    var pk = testasd.value;
}

Solution

  • I believe you have to check for checked. Add :checked in querySelector. Adding solution there:

    const testasd = document.querySelector('input[type=radio][name=pkyes]:checked');        
    const pk = testasd ? testasd.value : '';
    console.log(pk)
    <div id='testtwo' style="display:block;">
      <label class="control-label col-sm-4" for="pnl">Is the packing properly vacuum sealed? :</label>
      <div class="col-sm-4" style="margin-top:19px;">
        <p class="form-control-static" style="margin-top: -7px;display: inline-flex;color: darkslategrey;">
            <input type="radio" name="pkyes" value="YES">
              <label for="pkyes" style="margin-left: 6px; margin-top: 8px;">YES</label><br>
              
            <input type="radio" name="pkyes" value="NO" style="margin-left: 16px;" checked>
              <label for="pkno" style="margin-left: 6px; margin-top: 8px;">NO</label><br>  
        </p>
      </div></div>