Omri Omri - 6 months ago 19
jQuery Question

Disable textbox after switching between radio buttons

I have the following code. Is there's a smart way to disable textbox and clear his value after switching between the the radio buttons?

<div class="checkbox">
<label style="margin-bottom:10px">Number of...:</label>
<div class="input-group" style="margin-bottom:10px">
<input class="radio" name="2" type="radio" checked="checked" id="numOfRadio" style="display:block;float:left">
<input class="form-control" name="numOf" type="number" placeholder="1000" value="1000" id="numOf" style="width:140px" />
<label for="radio_2" style="font-weight:400"><input type="radio" name="2" id="radioAll" style="margin-left" />All</label>
</div>
</div>


I try to use the following code, but it didn't help:

$('.radio').on('click', function() {
$('.radio')
.siblings()
.prop('disabled', true);

$(this)
.siblings()
.prop('disabled', false);
});

Answer

Try this. The second radio is inside a label. So siblings is not enough. Get the parent div and use that to get to the input using find.

$('.radio').on('change', function() {
  $(this)
    .closest('div').find('input[type="number"]')
    .prop('disabled', this.id == 'radioAll');
    $(".form-control").val("");
    $(".form-control").removeAttr("placeholder");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="checkbox">
  <label style="margin-bottom:10px;">Number of...:</label>
  <div class="input-group" style="margin-bottom:10px">
    <input class="radio" name="2" type="radio" checked="checked" id="numOfRadio" style="display:block;float:left">
    <input class="form-control" name="numOf" type="number" placeholder="1000" value="1000" id="numOf" style="width:140px" />
    <label for="radioAll" style="font-weight:400">
      <input class="radio" type="radio" name="2" id="radioAll" style="margin-left" />All
    </label>
  </div>
</div>