Make A Textbox Appear When A Value Is Selected From A Dropdown List In Mvc
When 'Other' is selected from the DDL all I want is for the textbox to appear. However it always displays instead of being hidden until called. My view markup is:
$("#OtherSpecify") is your textbox.
If you are using jQuery you shoud use it all the time.
Use $(handler) insted of
DOMContentLoaded
event:<div class="form-group">
<divclass="col-md-1">
@Html.DropDownList("SelectType", new List<SelectListItem> {
new SelectListItem{Text = "test 1", Value = "1"},
new SelectListItem{Text = "test 2", Value = "2"},
new SelectListItem{Text = "Other", Value = "3"}
}, new { @id = "SelectType" })
@Html.TextBox("OtherSpecify", "")
</div></div>@sectionScripts {
<script>
$(function() {
$("#SelectType").on("change", function() {
if (parseInt($("#SelectType").val()) == 3) {
$("#OtherSpecify").show();
} else {
$("#OtherSpecify").hide();
}
});
$("#SelectType").trigger("change");
});
</script>
}
Remember to place script after jQuery library is loaded. In most cases @section Scripts
do the work.
Solution 2:
I have to adjust a few things to enable the Javascript to work. Firstly I seperated out my HTML helpers:
<div class="form-group">
@Html.LabelFor(model => model.SelectType, "Select Type", new { @class = "control-label col-md-5" })
<div class="col-md-1">
@Html.DropDownList("SelectType", String.Empty)
@Html.ValidationMessageFor(model => model.SelectType)
</div>
</div>
<divclass="form-group"id="OtherSpecifyFormGroup">
@Html.LabelFor(model => model.OtherSpecify, new { @class = "control-label col-md-4" })
<divclass="col-md-4 sbchanged">
@Html.TextBoxFor(model => model.OtherSpecify)
@Html.ValidationMessageFor(model => model.OtherSpecify)
</div></div>
Then wrote the following JavaScript code:
<script>
$(document).ready(function () {
//this line fires no matter what
$("#OtherSpecifyFormGroup").hide();
$("#SelectType").change(function () {
var value = document.getElementById("SelectType").value;
if (value == "4") {
$("#OtherSpecifyFormGroup").show("highlight", { color: "#7FAAFF" }, 1000);
}
else {
$("#OtherSpecifyFormGroup").hide();
}
});
})
</script>
I gave my form group for Other Specify an ID so that I could initially hid the textbox. Then declared the variable "value" as in my database the values that populate the DDL have SelectType Ids, therefore it wouldn't call "Other" as it wasn't recognised but as shown when the value "4" is called it works! The else ensures that if any other DDL value is selected then the textbox is hidden again.
Post a Comment for "Make A Textbox Appear When A Value Is Selected From A Dropdown List In Mvc"