Search code examples
javascriptonchange

Textbox become readonly base on dropdown selected value


How can I change the attribute of my textbox to readonly instead of hiding it?

Dropdown:

<div class="form-group">
@Html.LabelFor(model => model.CIVSTAT, "Civil Status", htmlAttributes: new { @class = "control-label" })    
<select class="form-control" id="CIVSTAT" name="CIVSTAT">
<option> </option>
<option>Single</option>
 <option>Married</option>
<option>Widowed</option>
<option>Separated</option>
<option>Divorced</option>
</select>
@Html.ValidationMessageFor(model => model.CIVSTAT, "", new { @class = "text-danger" })
</div>

Textbox:

 <div class="form-group">
    @Html.LabelFor(model => model.SPOUSE, "Spouse", htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.SPOUSE, new { htmlAttributes = new { @class = "form-control", @autocomplete = "off", placeholder = "Spouse's Name", maxlength = 40, @id="spouse" } })
    @Html.ValidationMessageFor (model => model.SPOUSE, "", new { @class = "text-danger" })
 </div>

JS Code:

  < script >
    $("#CIVSTAT").change(function () {
        if ($(this).val() == "Single") {
            $('#spouse').hide();                       
        }else {
            $('#spouse').show();               
        }
    });


Solution

  • Please try with below code snippet.

    $("#CIVSTAT").change(function () {
        if ($(this).val() == "Single") {
            $('#spouse').attr('readonly', true);                       
        }else {
            $('#spouse').removeAttr('readonly');               
        }
    });