Set radio input as checked in modal using Javascript

Asked

Viewed 45 times

0

I have a modal that receives data from a BD. Data transport is ok.

One of the camps is like radio, with the following code:

<div class="row">
  <label class="col-1"><strong>Status:</strong></label>
  <div class="col-11">
    <div class="custom-control custom-radio custom-control-inline">
      <input name="status" id="status0" type="radio" required="required" class="custom-control-input" value="A">
      <label for="status0" class="custom-control-label">Ativo</label>
    </div>
    <div class="custom-control custom-radio custom-control-inline">
      <input name="status" id="status1" type="radio" required="required" class="custom-control-input" value="D">
      <label for="status1" class="custom-control-label">Inativo</label>
    </div>
  </div>
</div>

This field receives from the BD the values "A" (Active) or "I" (Inactive). I need to assign checked to one of the options via Javascript but it is not working.

The code fragment that does this task is this one:

var status = button.data('status');
if (status == "A") {
  modal.find('#status0').checked;
}
else if (status == "I") {
  modal.find('#status1').checked;
}
else {
  alert("Valor indefinido para o campo Status");
}

I tried with Document.getElementById(status0) unsuccessful.

I tried with Document.getElementsByName("status")[status0] unsuccessful.

1 answer

0


I was able to solve by changing the Javascript code to:

if (status == "A") {
  $('input[id=status0]').prop('checked', true);
}
else if (status == "I") {
  $('input[id=status1]').prop('checked', true);
}
else {
  alert("Valor indefinido para o campo Status");
}

The status checked it’s actually a property.

  • 1

    Just use, for example, $('#status0').prop('checked', true);. The symbol # means the id of the element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.