2

我如何提醒选择在纯 JavaScript 中不能为空白?

这是我的选项菜单的代码:

            <div class="interest">
            <label for="interest">Interest Area *</label>

            <select name="interest">
            <option value="blank"></option>
            <option value="option1"> EXAMPLE 2 </option>
            <option value="option2"> EXAMPLE 3 </option>
            <option value="option3"> EXAMPLE 4 </option>
            </select>
            </div>

提前致谢

4

4 回答 4

7
document.getElementsByName('interest')[0].onchange = function() {
     if (this.value=='blank') alert('Select something !');
}

或在提交处理程序或类似处理程序中,只需检查值

if ( document.getElementsByName('interest')[0].value == 'blank' )
    alert('Select something !');
于 2014-01-01T18:35:38.130 回答
0

通常,在简单的 if 语句中检查 selectElement.value 是否为“空白”。

于 2014-01-01T18:29:52.687 回答
0

您可以使用 '.selectedIndex' 返回所选值的索引并检查其是否等于空白(在您的情况下为 0)

if(0 == document.getElementsByTagName('select')[0].selectedIndex){
alert("Please select a value first")
return;
}

您也可以使用 Jquery 代替 document.getElementsByTagName 进行选择

于 2014-01-01T18:44:20.827 回答
0

我觉得最简单的方法是使用 html 在 select all the best 上使用 required

兴趣区 *

        <select required name="interest">
        <option value="blank"></option>
        <option value="option1"> EXAMPLE 2 </option>
        <option value="option2"> EXAMPLE 3 </option>
        <option value="option3"> EXAMPLE 4 </option>
        </select>
        </div>
于 2018-11-18T23:29:04.773 回答