Home > Net >  JS select lenght without ID
JS select lenght without ID

Time:09-07

I'm trying to collect the lenght of several select. How can I know the lenght of each select? The way I found is $('#mylist option').length which seems not feasible in this case since I don't have IDs for each select. The console.log shown below always return "1" even though there are select with multiple lines.

JS code:

$('#severalStores').find('.selectLimitInformation').each(function () {
    console.log($(this).length); //Always return "1"
});

HTML code:

<div  id="severalStores">
    <div >
        <div >
            <div >
                <label>Store AAA:</label>
            </div>
            <div >
                <select >
                    @foreach (...) //data from ViewBag
                    {
                        <option value="@storeLimit.info">@storeLimit.description</option>
                    }
                    <option value="0">Not available</option>
                </select>
            </div>
        </div>
        <div >
            <div >
                <label>Store BBB:</label>
            </div>
            <div >
                <select >
                    @foreach (...) //data from ViewBag
                    {
                        <option value="@storeLimit.info">@storeLimit.description</option>
                    }
                    <option value="0">Not available</option>
                </select>
            </div>
        </div>
        //Several other select
    </div>
</div>

CodePudding user response:

You almost had it.

First, you loop through the selects. You don't need to use find in your case. Then in your loop you do use find to find the length of options that are children of the select.

$('#severalStores .selectLimitInformation').each(function () {
    console.log($(this).find("option").length); //Always return "1"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="severalStores">
    <div >
        <div >
            <div >
                <label>Store AAA:</label>
            </div>
            <div >
                <select >
                       <option value="@storeLimit.info">@storeLimit.description</option>
                    <option value="0">Not available</option>
                </select>
            </div>
        </div>
        <div >
            <div >
                <label>Store BBB:</label>
            </div>
            <div >
                <select >
                        <option value="@storeLimit.info">@storeLimit.description</option>
                    <option value="0">Not available</option>
                </select>
            </div>
        </div>
        //Several other select
    </div>
</div>

  • Related