我需要确保选择了一位艺术家,但不确定我是否应该使用"艺术家"或"选择"。我试过了两个,但它没有用。如果没有选择,代码必须显示警告。
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>
&#13;
答案 0 :(得分:0)
您可以使用selectedIndex
;
function validate() {
var select_artist = document.getElementById('artistselect');
if (select_artist.selectedIndex < 1) {
alert("You need to choose an artist");
return false;
}
}
此外,您正尝试使用div元素获取所选选项。而是设置select
元素的id属性。
<select name="select" id = "artistselect">
答案 1 :(得分:0)
function validate() {
var select_artist = document.getElementById('select');
if(select_artist.selectedIndex == 0)
alert("You need to choose an artist")
}
&#13;
<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>
&#13;