Show / hide control based on mvc 4 razor C # drop down list

Here is my code

@Html.DropDownListFor(z => z.SelectedReportId, new SelectList(Model.ReportTypes, "Value", "Text", Model.SelectedReportId), "-- Select Report --") @Html.CheckBoxFor(model => model.IncludePhotos)@Html.LabelFor(model => model.IncludePhotos) 

What generates:

 <select data-val="true" data-val-number="The field SelectedReportId must be a number." data-val-required="The SelectedReportId field is required." id="SelectedReportId" name="SelectedReportId"> <option value="">-- Select Report --</option> <option value="1">Excel Report</option> <option value="2">Text Report</option> </select> <br /> <input data-val="true" data-val-required="The Include photos in the report field is required." id="IncludePhotos" name="IncludePhotos" type="checkbox" value="true" /> 

I have one drop-down list and a checkbox, I need to disable this checkbox if the user selects the first value in the drop-down list. Here is the javascript that I use without success

 $(function () { $('#SelectedReportId').change(function () { var value = $(this).val(); if (value == '1') { $('#IncludePhotos').show(); } else { $('#IncludePhotos').hide(); } }); }); 

Appreciate any help, thanks

+6
source share
2 answers

Included javascript inside the {s} section of @section scripts and started working,

 @section scripts{ <script type="text/javascript"> $(function () { $('#SelectedReportId').change(function () { var value = $(this).val(); if (value == '1') { $('#IncludePhotos').show(); } else { $('#IncludePhotos').hide(); } }); });</script>} 
+7
source

try it

@Html.DropDownListFor(z => z.SelectedReportId, new SelectList(Model.ReportTypes, "Value", "Text", Model.SelectedReportId),new {id="myDropdown"}

@Html.CheckBoxFor(model => model.IncludePhotos,new {id="myCheckbox"})

$(function () { $('#myDropdown').change(function () { var value = $(this).val(); var fistVal=$('#myDropdown option:first-child').attr("selected", "selected"); if (value == fistVal) { $('#IncludePhotos').show(); } else { $('#IncludePhotos').hide(); } }); });

+1
source

Source: https://habr.com/ru/post/982703/


All Articles