I'm using BeginCollectionItem and I'm trying to figure out how to get each individual collection value to do conditional show/hide logic. For example, if I have the following razor markup:
<div class="collection">
@using (Html.BeginCollectionItem(nameof(Item)))
{
<select class="select-class" id="select-id" asp-for="SelectExample">
<option value="a">a</option>
<option value="b">b</option>
</select>
<div class="show-if-b">b is selected</div>
}
</div>
I need to show the "show-if-b" div if the "b" element is selected, else it needs to hide. This logic needs to run onchange of the select and when the page loads ("b" could be saved) so I don't always have an event to attach to.
I've tried different approaches with jQuery .closest(), .find(), and .parents() but I can't seem to get the specific select value in each collection.
Any help is greatly appreciated.
You can use $(this).next()
in on("change")
to select your each div element which has "b is selected"
. I set these elements style display none as a default but you can change this css property according to your model initial value. You can implement like following.
$(".collection .select-class").on("change", function(){
var val = $(this).val();
if(val == "a")
{
$(this).next().hide();
}
else
{
$(this).next().show();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collection">
<table>
<tr>
<select style="float:left" class="select-class" id="select-id" asp-for="SelectExample">
<option value="a">a</option>
<option value="b">b</option>
</select>
<div class="show-if-b" style="display:none">b is selected</div>
</tr>
<tr>
<select style="float:left" class="select-class" id="select-id" asp-for="SelectExample">
<option value="a">a</option>
<option value="b">b</option>
</select>
<div class="show-if-b" style="display:none">b is selected</div>
</tr>
<tr>
<select style="float:left" class="select-class" id="select-id" asp-for="SelectExample">
<option value="a">a</option>
<option value="b">b</option>
</select>
<div class="show-if-b" style="display:none">b is selected</div>
</tr>
</table>
</div>