简体   繁体   中英

Selecting from a dropdown box

I need to make sure an artist has been selected, but not sure if i should be using "artist" or "select". I have tried both and it's not working. The code must show an alert if there is no selection.

 function validate() { var select_artist = document.getElementById('artist'); if (artist == "") { alert("You need to choose an artist"); return false; } 
 <div id="artist"> <p>Select an Artist: <select name="select"> <option value="0">Choose Artist</option> <option value="1">Bobby Smith</option> <option value="2">The Vibes</option> <option value="3">Kids of Rock</option> </select> </div> 

You could use selectedIndex ;

function validate() {

    var select_artist = document.getElementById('artistselect');
    if (select_artist.selectedIndex < 1) {
        alert("You need to choose an artist");
        return false;
    }
}

Also, you are trying to get the selected option by using div element. Set id attribute for select element instead.

<select name="select" id = "artistselect">

 function validate() { var select_artist = document.getElementById('select'); if(select_artist.selectedIndex == 0) alert("You need to choose an artist") } 
 <div id="artist"> <p>Select an Artist: <select id="select" onchange="validate()"> <option>Choose Artist</option> <option >Bobby Smith</option> <option>The Vibes</option> <option>Kids of Rock</option> </select> </div> 

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