Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET / CSS Foreach Checkboxes Individual Styling

Tags:

c#

css

razor

I have a foreach loop creating CheckBoxes, causing them to all have the same ID. I've got some CSS but when you check any box it puts the css onto the first iteration, how do I add some dynamic ID sort of thing to only add the css to the selected box?

Loop:

@foreach (var item in Model.Where(p => p.UserTable.ID == ViewBag.UserTableID))
{
    <tr>
        <td>
            <div class="select">
                <input type="checkbox" id="select" name="" />
                <label for="select"></label>
            </div>

css:

.select {
width: 20px;
position: relative;
}

.select label {
    cursor: pointer;
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: #eee;
    border: 1px solid #ddd;
}

    .select label:after {
        opacity: 0.2;
        content: '';
        position: absolute;
        width: 9px;
        height: 5.5px;
        background: transparent;
        top: 4.8px;
        left: 5.4px;
        border: 3px solid #333;
        border-top: none;
        border-right: none;
        transform: rotate(-45deg);
    }

.select label:hover::after {
opacity: 0.5;
}

.select input[type=checkbox]:checked + label:after {
opacity: 1;
}
like image 505
liamcook Avatar asked Jun 12 '26 02:06

liamcook


1 Answers

Why not just assign each element their item's ID?

<div class="select">
    <input type="checkbox" id="[email protected]" />
    <label for="select"></label>
</div>

Unless you have duplicates in that list, they'll always be unique.

By the way: your View shouldn't be filtering out items, it should be given only the items it needs (that Where should be done at the database level)

like image 87
Camilo Terevinto Avatar answered Jun 13 '26 16:06

Camilo Terevinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!