简体   繁体   中英

How would I validate my Scrolling List with my current code?

So I am trying to create a function that will validate if an option is selected in my Scrolling List. If nothing is selected, and alert will go off, if one is selected, then it passes validation. This is the code I am using:

<select id="topList" name="toppings" size="8" multiple>
                               <option value="opCream">Whipped Cream</option>
                               <option value="opFudge">Hot Fudge</option>
                               <option value="opMarsh">Marshmallow</option>
                               <option value="opCherry">Cherries</option>
                               <option value="opChocSprinkles">Chocolate Sprinkles</option>
                               <option value="opRainSprinkles">Rainbow Sprinkles</option>
                               <option value="opCheese">Cheesecake</option>
                               <option value="opOreo">Oreo Crumbles</option>
                           </select>

function checkScrollList() {
                    var ddl = document.getElementById("topList");
                    var selectedValue = ddl.options[ddl.selectedIndex].value;
                    if (selectedValue == false)
                    {
                        alert("Please select a sundae topping.");
                    }
                }

Thanks for the suggestions!

You could use the selectedIndex property of the select object, like this:

function checkScrollList() {
    var ddl = document.getElementById("topList");
    if (ddl.selectedIndex === -1) {
         alert("Please select a sundae topping.");
    }
}

The selectedIndex property will give the zero-based index of the first selected option, so it is not useful for actually retrieving all the selected options. But it is guaranteed to be -1 when no options are selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM