Home Ask Login Register

Developers Planet

Your answer is one click away!

skiskd February 2016

How to disable TextAreaFor?

How to disabled text are in mvc. I am using mvc 4.0. below is my code, I want to make conditionally means if m.Changes values length >0 then it should be disable,else it is enabled. how that be possible?

@Html.TextAreaFor(m => m.Changes , new { style = " width:97%; height:50px;", tabindex = 5 }) 

Answers


Balázs February 2016

Conditional disabling is only possible by using JavaScript. First, you need to set an id:

@Html.TextAreaFor(m => m.Changes , new { style = " width:97%; height:50px;", tabindex = 5, id = "someId" }) 

And assuming you use jQuery:

$('#someId').on('keyUp', function() {
    var text = $('#someId').val();
    if (text.length > 0)
      $('#someId').attr('disabled','disabled');
});

I'd like to note, however, that disabling some textbox when the length of it's content is greater than zero, that is, it has any content, just makes no sense, since disabling it will prevent you from modifying it ever again (unless there is some logic that programmatically re-enables it based on some condition).

If your goal is to disable the control if the length of the value on the server is greater than zero (that is, the Changes property has a not null and non-empty value inside the model), then you could do this:

@if (Model.Changes.Length > 0) {
   @Html.TextAreaFor(m => m.Changes , new { style = " width:97%; height:50px;", tabindex = 5, id = "someId", disabled = "disabled" }) 
} else {
   @Html.TextAreaFor(m => m.Changes , new { style = " width:97%; height:50px;", tabindex = 5, id = "someId" }) 
}

If you need to disable it based on a client-side condition, then you can't avoid writing a scipt to do that.


CodeCaster February 2016

It is not trivial, because the presence of the disabled attribute will already disable the element, whether or not the attribute actually has a value.

So you can't do something like this:

new { disabled = Model.Changes.Length == 0 } 

You could write an extension method that supports this, as shown in Set disable attribute based on a condition for Html.TextBoxFor. This extension method has a bool disabled parameter, which when true will insert the proper disabled="disabled" attribute.

Post Status

Asked in February 2016
Viewed 2,309 times
Voted 7
Answered 2 times

Search




Leave an answer


Quote of the day: live life