Reputation: 181
I'm doing some HTML in MVC and have two text boxes in my view. I have to show the weight textbox if age 10 to 30 is entered. If not, then don't show or hide if changed. I'm not sure how to achieve this using jQuery.
<fieldset>
<legend>
<h3>Details</h3>
</legend>
<div class="field colon">
<label>Enter Age</label>
@Html.TextBoxFor(m => m.Age, new { @class ="text210" })
</div>
<div class="field colon">
<label>Enter Weight</label>
@Html.TextBoxFor(m => m.Weight, new { @class ="text210" })
</div>
</fieldset>
Upvotes: 0
Views: 181
Reputation: 25351
You can use this jQuery code to hide and show the parent div
of the weight depending on the age value:
$("#@Html.IdFor(m => m.Age)").on("change", function() {
if (this.value > 9 && this.value < 31)
$("#@Html.IdFor(m => m.Weight)").parent().hide();
else
$("#@Html.IdFor(m => m.Weight)").parent().show();
});
If you want to start with the weight hidden, add this CSS to its div
:
<div class="field colon" style="display: none;">
Here is a demo, I converted the ASP code to its HTML equivalent:
$("#Age").on("change", function() {
if (this.value > 9 && this.value < 31)
$("#Weight").parent().hide();
else
$("#Weight").parent().show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<legend>
<h3>Details</h3>
</legend>
<div class="field colon">
<label>Enter Age</label>
<input type="text" id="Age" name="age" />
</div>
<div class="field colon" style="display: none;">
<label>Enter Weight</label>
<input type="text" id="Weight" name="Weight" class="text210" />
</div>
</fieldset>
Upvotes: 2