enable @Html.editorFor based on checkbox selection

Hi I am still very new to web design and languages including JavaScript.

In a strongly typed cshtml view, is it possible to only show a textfield based on a checkbox (where both the textfield and the checkbox are strongly typed to the model?) I created a example scenario below:

Sample Class:

namespace FruitSurveyNameSpace
    public class FruitSurvey 
        public bool likesFruit { get; set; }
        public string fruitName { get; set; }

Sample cshtml:

<!DOCTYPE html>
@using FruitSurveyNameSpace
@model FruitSurvey
@using (Html.BeginForm())

        <p>Like Fruit? @Html.EditorFor(model => model.likesFruit) </p>
        <p>Which Fruit: @Html.EditorFor(model => model.fruitName)</p>

@section Scripts {

which generates the following html

<form action="/" method="post">
  <input name="__RequestVerificationToken" type="hidden" value="blahValue" />
      <input class="check-box" data-val="true" data-val-required="The likesFruit field is required." id="likesFruit1" name="likesFruit1Name" type="checkbox" value="true" />
      <input class="text-box single-line" id="fruitName1" name="fruitName1Name" type="text" value="" />

As in the sample scenario above, it only makes sense for the user to input the fruit name once he/she selects that he/she likes fruit (dynamically). Otherwise, the fruit name input doesn't have any meaning and should not be displayed. Furthermore, we probably enforce the user to input the fruit name once the he/she selects like fruit checkbox (currently I am using [Required] attribute in non dynamically generated fields and not sure if it would still work if becoming dynamic).

As we can see, both values are strongly typed to the model, and that's why I'm using html helpers. Is there a way to do so without using JavaScript? Or if there isn't, how should I do so in combination with html helpers?

Many thanks in advance.



For the validation, you would need a [RequiredIf] attribute. There a many examples on SO or you can look at the MVC Foolproof Nuget package

As Rowan indicated, a 2 step wizard would be required if javascript is not acceptable. If you can use javascript, then its simply a matter of toggling the textbox visibility based on the checked state of the checkbox.

Based on the html above

$('#likesFruit1').click(function() {

This assumes that the the checkbox is initially checked, and the textbox is initially visible. Note also that this only toggles the textbox. If you have associated labels and/or text where all the elements are wrapped in a container (say a div) then you might want


so that the associated elements are also toggled.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.