简体   繁体   中英

jquery check if option is selected

I am having a situation where i need to see if an option is selected or not.When i click a button, if an option is not selected, the select box should turn red and give me an alert. It does not work. I am having difficaulty with the if statement. Any solution?

Javascript

$(document).ready(function(){

var $films = [];

$("#button").click(function(){
    var $titelBetyg = [];

    var $titel = $('#name').val();
    var $betyg = $('#options').val();

    if($titel == ""){
        $('#name').css('background-color', 'red');
        alert("Fail");
    }
    else if($betyg == "0"){
        $('#options').css('background-color', 'red');
        alert("Fail");
    }
    else{
        $titelBetyg.push($titel);
        $titelBetyg.push($betyg);
        $films.push($titelBetyg);
    }

    $('#rightbar').append($films);
});

});

HTML

<body>
<div id="page">
    <div id="header">
        <h1> Min filminsamling </h1>
    </div>
    <div id="leftbar">
        <form>
            <fieldset>
                <legend>Lägg till en film:</legend>
                Titel:
                <br><input type="text" name="name" id="name"><br>
                Betyg:
                <br><select id="options">
                    <option>Välj betyg här...</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>                        
                </select>
                <br><input type="button" name="button" value="Spara film" id="button">
            </fieldset>
            <fieldset>
                <legend>Sortera film:</legend>
                <input type="button" name="stigande" value="Högst betyg" id="stigande">
                <br><input type="button" name="fallande" value="Lägst betyg" id="fallande">
            </fieldset>
        </form>
    </div>
    <div id="rightbar">
        Filmer
    </div>
</div>
</body>

$betyg == "0" isn't working because it isn't a possibility according to the UI.

Your default option is... nothing. Perhaps an empty string, "" ; nowhere does 0 appear.

Explicitly set an option to check for, and check for it.

When you check whether to warn that nothing is selected, you look to see if the value of "option" is "0". Yet you didn't actually define the value of "0" for no selection, you only defined values "1" through "5". I'm not sure what to expect with Javascript if you ask for the value of something whose value is undefined; my first suggestion would be to define the value "0" for no selection and see if it helps. :)

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