检查下拉选择的选项是否不是JavaScript的第一个选项 [英] Check if dropdown's selected option is not the first with JavaScript

查看:95
本文介绍了检查下拉选择的选项是否不是JavaScript的第一个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我在HTML代码中的选项:

 < label id =subn> 
< select name =subsid =subs>
< option value =nothing>选择主题< / option>
< option value =一般问题>一般问题< / option>
< option value =MemberShip Area> MemberShip Area< / option>
< option value =其他>其他< / option>
< / select>
< / label>

我想要创建JavaScript代码来检查用户是否选择了第一个选项。 / p>

这是我试过的:

  if(document.getElementsByTagName 'option')==nothing){
document.getElementById(subn)。innerHTML =Subject is Required!;
document.getElementById(subs)。focus();
返回false;


解决方案

nothing 将会是第一个(通常是我的经历):

  if(document.getElementById('subs')。selectedIndex == 0){

比较基于值,做到这一点:

  var sel = document.getElementById('subs'); 
if(sel.options [sel.selectedIndex] .value =='nothing'){



<

 < select name =subs你可以改变你的标记,使标签在旁边,如下所示: id =subs>< / select>< label id =subnfor =subs>< / label> 

否则这部分: .innerHTML =Subject is Required!; 会清除你的< select> :)

Below are the options that i have in my HTML code:

    <label id="subn">
      <select name="subs" id="subs">
        <option value="nothing">Choose a Subject</option>
        <option value="General Question">General Question</option>
        <option value="MemberShip Area">MemberShip Area</option>
        <option value="Others">Others</option>
      </select>
    </label>

I want to create JavaScript code that will check if the user selected an option other than the first.

Here is what I tried:

if (document.getElementsByTagName('option') == "nothing"){
    document.getElementById("subn").innerHTML = "Subject is Required!";
    document.getElementById("subs").focus();
    return false;
}

解决方案

You can check like this if nothing is going to be first (usually the case in my experience):

if (document.getElementById('subs').selectedIndex == 0){

To still compare based on the value, do this:

var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {

You may wand to change your markup so the label is beside, like this:

<select name="subs" id="subs"></select><label id="subn" for="subs"></label>

Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)

这篇关于检查下拉选择的选项是否不是JavaScript的第一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆