user2751035
user2751035

Reputation: 103

How to Disable a text field based on Radio Buttonin HTML?

The textfields should be disabled unless radio buttons are clickedI have the following textfield and I want to enable it when radio button clicked otherwise it should be disabled:

function Chosen4() if (document.getElementById('rbothers4').checked == true) {
      message += " (Others)"
     document.getElementById("cbotherstext4").setAttribute("disabled", true);
}

And HTML code is here

<input type="radio" name="Promised" id="rbothers4" onclick="displayResult(this.value)"   value="Yes6" >c. Others
       (Please Specify)
<input id="cbotherstext4" type="text" />&nbsp;</td>
<input type="button" id="Button4" onclick="Chosen4()" value="Date Promised"/>

Upvotes: 0

Views: 2637

Answers (1)

mplungjan
mplungjan

Reputation: 178403

  1. You do not have a checkbox in your example.
  2. Do not use inline event handling
  3. IF you choose to do it anyway, pass the object to the function

JavaScript solution

Live Demo

window.onload=function() {
  var promised = document.getElementsByName("Promised4");
  for (var i=0;i<promised.length;i++) {
    promised[i].onclick=function() {
      var rads = this.form[this.name];
      for (var i=0;i<rads.length;i++) {
        var textField = this.form[rads[i].value.toLowerCase()+"Specify"];
        if (textField) textField.disabled = !rads[i].checked;
      }    
    }    
  }
}       

jQuery solution

Live Demo

$(function() {
  var $promised = $("input[name='Promised4']");
  $promised.each(function() {
    $(this).on("click",function() {
      $promised.each(function() {
        var textField = $(this).nextAll("input").first();
        if (textField) textField.prop("disabled",!this.checked);
      });    
    });    
  });
});       

using

<form>
  <input type="radio" name="Promised4" id="rbYes" value="Yes" ><label for="rbYes">a. Yes</label><br/>
  <input type="radio" name="Promised4" id="rbNo"  value="No" ><label for="rbNo">b. No (please specify)</label>
  <input type="text" name="noSpecify"  id="noSpecify" value="" disabled="disabled" /><br/>
  <input type="radio" name="Promised4" id="rbOther" value="Other" ><label for="rbOther">c. Other (please specify)</label>
  <input type="text" name="otherSpecify" id="otherSpecify" value="" disabled="disabled"/><br/>
</form>

Upvotes: 3

Related Questions