7

I need to disable an input dynamically when its value is equal to "*". How can I achieve this using the MVC Razor?

    @Html.TextBoxFor(m => m.Digits[0], new { @class = "form-control input-lg label_16", @placeholder = 
"1st", (Model.Digits[0] == "*" ? "disabled" : "") })

The above code doesn't compile Is this possible?

1
  • what do you mean by dynamically? Do you want the TextBox to change to disabled when user enter * or when the m.Digit[0] is * ? Commented Oct 3, 2014 at 13:37

1 Answer 1

17

Try using ternary operator

@Html.TextBoxFor(m => m.Digits[0], Model.Digits[0] == "*" ? (object)new { @class = "form-control input-lg label_16", @placeholder = 
"1st", @disabled = "disabled" } : new { @class = "form-control input-lg label_16", @placeholder = 
"1st" })

in the code above, the second parameter of @Html.TextBoxFor helper method will be based on the value of Model.Digits[0]. If it's * then the parameter would include the disabled attribute

new { @class = "form-control input-lg label_16", @placeholder = 
"1st", @disabled = "disabled" }

otherwise

new { @class = "form-control input-lg label_16", @placeholder = 
"1st" }
Sign up to request clarification or add additional context in comments.

2 Comments

I tried your code before asking this question, it produces the following output: disabled="disabled" or disabled. In both cases the input box is disabled!
Please try the updated answer, I have tested it and it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.