So_oP
So_oP

Reputation: 1293

MVC5 dynamically disable textbox based on another textbox value

I have MVC5 project and have 2 text box's fields(client id, document id) and one drop-down list.

I would like dynamically enable or disable client id text box and drop down list based on document id value, for example, if I wrote something in document id text box I would like to see client id text box and drop down list disabled, if I delete text from document id text box I would like to see enabled client id text box and drop-down list.

So far I have done research and to be honest, could not manage to find an exact answer. I read something about jquery but I am very weak at javascript.

Here is my code. How can I achieve the desired result?

<span>@Html.DisplayNameFor(model => model.ClientId).ToString():</span>
@Html.TextBox("ClientId", Model.Count()>0? Model.FirstOrDefault().ClientId:"", new { @class = "inline" })

<span>@Html.DisplayNameFor(model=>model.DocumentIdentificationId).ToString():</span>
@Html.TextBox("DocumentIdentificationId", Model.Count() > 0 ? Model.FirstOrDefault().DocumentIdentificationId: "", new {@class = "inline" })

<span>@Html.DisplayNameFor(model => model.DocumentType).ToString():</span>
@Html.DropDownList("DocumentTypes", new SelectList(documentTypes, "DocType", "DocName"),"", new { @class = "inline" }) 

Upvotes: 1

Views: 1185

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18973

You can write a script to do this.

Because @Html.TextBox("ClientId", Model.Count()>0? Model.FirstOrDefault().ClientId:"", new { @class = "inline" }) will generate a input tag with id = ClientId

You can use change event or keyup event for your requirement.

$("#ClientId").keyup(function(){
   if($(this).val() != ""){
      $("#DocumentIdentificationId").attr("disabled", "disabled"); 
      $("#DocumentTypes").attr("disabled", "disabled"); 
   }else{
      $("#DocumentIdentificationId").prop("disabled", false); 
      $("#DocumentTypes").prop("disabled", false); 
   }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <input type="text" id="ClientId" />

   <input type="text" id="DocumentIdentificationId" />

    <select id="DocumentTypes">
       <option>Test<option>
    </select>

Upvotes: 3

Related Questions