user7357089 user7357089 - 4 years ago 155
Javascript Question

How to enable and disable textbox based on option button More then one field

I found the below code to enable and disable textbox based on the option button but i want to more than 20 fields like that.

I want to write lot of scripts for that, is there easy way to create 20 fields like that

Please any one help me regarding this



$(window).load(function() {
$(function() {
window.invalidate_input = function() {
if ($('input[name=opt13]:checked').val() == "Yes")
$('#others').removeAttr('disabled');
else
$('#others').attr('disabled', 'disabled');
};

$("input[name=opt13]").change(invalidate_input);

invalidate_input();
});
}); //]]>

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<label>Did you study any school</label>&nbsp&nbsp
<input type='radio' name='opt13' value='Yes' id="" />Yes
<input type='radio' name='opt13' value='No' id="" />Others</td>
<br />
<br />
<label>Enter MatexBranch:</label>&nbsp;&nbsp;
<input type="textbox" name="others" id="others" />




Answer Source

First, to make code reusable, remove any specific code like $("#..."). Instead, navigate to element using this. For this, you can use .siblings function of jquery.

Also there is not need for if...else. You can set value as true or false to enable/ disable element.

Also, instead of binding change on radio using name, do it using a combination of selector as name will be different for every group.

$(function() {
  var invalidate_input = function() {
    $(this).siblings('.input-value').attr('disabled', $(this).val() !== "Yes");
  };

  $(".section input[type='radio']").on("change", invalidate_input);
});
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>

<div class="section">
  <label>Did you study any school</label>&nbsp&nbsp
  <input type='radio' name='opt13' value='Yes' id="" />Yes
  <input type='radio' name='opt13' value='No' id="" />Others</td>
  <br />
  <br />
  <label>Enter MatexBranch:</label>&nbsp;&nbsp;
  <input type="textbox" name="others" class="input-value" />
</div>

<div class="section">
  <label>Did you study any school</label>&nbsp&nbsp
  <input type='radio' name='opt14' value='Yes' id="" />Yes
  <input type='radio' name='opt14' value='No' id="" />Others</td>
  <br />
  <br />
  <label>Enter MatexBranch:</label>&nbsp;&nbsp;
  <input type="textbox" name="others" class="input-value" />
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download