I have a country field and a state field. I want to show the state field when the user chooses United States. Otherwise, I want it to be hidden.
This is my js script:
@section Scripts {
<script type="text/javascript">
$("#Country").change(function () {
var value = $("#Country").val()
if (value === "1") {
$("#State").show();
}
if (value != "1") {
$("#State").hide();
}
});
</script>
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
This is my cshtml page of the form.
<div >
<label asp-for="Form.Country" ></label>
<select asp-for="Form.Country" >
<option disabled selected>Choose your Country</option>
<option>Canada</option>
<option>United States</option>
<option>Mexico</option>
</select>
<span asp-validation-for="Form.Country" ></span>
</div>
<div >
<label asp-for="Form.State" ></label>
<select asp-for="Form.State" asp-items="Model.States" >
<option disabled selected>Choose your State</option>
</select>
<span asp-validation-for="Form.State" ></span>
</div>
CodePudding user response:
- To use
$("#Country")
and$("#State")
you have to specifyid
's for the<select>
forms - To get the
.val()
of the selected item you have to specifyvalue
for each option
Your JS code may look like this:
$("#State").hide();
$("#Country").change(function () {
var value = $("#Country").val()
if (value === "2") {
$("#State").show();
}
else {
$("#State").hide();
}
});
HTML:
<div >
<label asp-for="Form.Country" ></label>
<select asp-for="Form.Country" id="Country">
<option disabled selected>Choose your Country</option>
<option value="1">Canada</option>
<option value="2">United States</option>
<option value="3">Mexico</option>
</select>
<span asp-validation-for="Form.Country" ></span>
</div>
<div >
<label asp-for="Form.State" ></label>
<select asp-for="Form.State" asp-items="Model.States" id="State">
<option disabled selected>Choose your State</option>
</select>
<span asp-validation-for="Form.State" ></span>
</div>
CodePudding user response:
Try Following Code:
HTML:
<div >
<label asp-for="Form.Country" ></label>
<select asp-for="Form.Country" id="Country">
<option disabled selected>Choose your Country</option>
<option value="0">Canada</option>
<option value="1">United States</option>
<option value="2">Mexico</option>
</select>
<span asp-validation-for="Form.Country" ></span>
</div>
<div id="state">
<label asp-for="Form.State" ></label>
<select asp-for="Form.State" asp-items="Model.States" >
<option disabled selected>Choose your State</option>
</select>
<span asp-validation-for="Form.State" ></span>
</div>
CSS:
#state{
display:none
}
Jquery:
$("#Country").change(function () {
var value = $("#Country").val();
console.log(value)
if (value === "1") {
$("#state").show();
}
if (value != "1") {
$("#state").hide();
}
});