Reputation: 45
I have am using html helper fields below, my issue I need the make these hiddenfor elements not hidden when checkbox is checked.
@Html.HorizontalFormFieldFor(model => model.InsaatHizmetBedeli)
<div class="control-group">
@Html.LabelFor(model => model.tadilatMi, new { @class = "control-label" })
<div class="controls">
@if (!Model.tadilatMi.HasValue)
{
Model.tadilatMi = false;
}
@Html.CheckBoxFor(model => model.tadilatMi.Value, new { @Name="tadilatmi" });
</div>
</div>
@Html.HiddenFor(model => model.myHiddenProperty)
here is my jquery code:
$("input[name='tadilatmi']").on("change", function () {
if ($("input[name='tadilatmi']").is(":checked")) {
$("#myHiddenProperty").show()
}
})
of course it not works.. how can I achieve this ?
Upvotes: 3
Views: 915
Reputation:
Your generating an input with type="hidden"
which is always hidden. The jQuery.show()
method is for toggling the display of elements styled with display:none;
and its changes it to display:block;
You could do this by changing the type
attribute
if ($("input[name='tadilatmi']").is(":checked")) {
$("#myHiddenProperty").attr('type', 'text')
}
or by making the input type="text"
and styling it as hidden
@Html.TextBoxFor(model => model.myHiddenProperty)
with the following css
#myHiddenProperty {
display: none;
}
and then your original script will work.
I suspect however that you want to toggle the visibility back if the checkbox is then unchecked, in which case you should have an else
block
if ($("input[name='tadilatmi']").is(":checked")) {
$("#myHiddenProperty").show()
} else {
$("#myHiddenProperty").hide()
}
Side note: your using an awful hack in order to make you checkbox bind to a nullable bool
property (by chaninging the name
attribute) and your label
does not even work as a label
(clicking on it will not toggle the checkbox
). I recommend you use a view model with
public bool Tadilatmi { get; set; }
and in the view simply use
@Html.LabelFor(m => m.Tadilatmi , new { @class = "control-label" })
<div class="controls">
@Html.CheckBoxFor(m => m.Tadilatmi);
</div>
and change the script to (which is more efficient)
var hiddenElement = $('#myHiddenProperty');
$('#tadilatmi').change(function () {
if ($(this).is(":checked")) {
hiddenElement.show()
} else {
hiddenElement.hide()
}
})
Your myHiddenProperty
property could then include a foolproof [RequiredIfTrue("Tadilatmi")]
or similar conditional validation attribute.
Upvotes: 1