如何检查是否从HTML下拉列表中选择了某个项目?

lit*_*326 11 html javascript html-select drop-down-menu

我有一个drop drown列表,我无法检查是否从下拉列表中选择了一个值

以下是我的HTML代码:

<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
    <option value="selectcard">--- Please select ---</option>
    <option value="mastercard">Mastercard</option>
    <option value="maestro">Maestro</option>
    <option value="solo">Solo (UK only)</option>
    <option value="visaelectron">Visa Electron</option>
    <option value="visadebit">Visa Debit</option>
</select><br/>
Run Code Online (Sandbox Code Playgroud)

以下是我的JavaScript代码:

var card = document.getElementByName("cards")[0].value;
if (card.value == selectcard) {
    alert("Please select a card type");
}
Run Code Online (Sandbox Code Playgroud)

Sac*_*hin 32

那么你错过了字符串selectcard应该是的引号"selectcard"

if (card.value == selectcard)
Run Code Online (Sandbox Code Playgroud)

应该

if (card.value == "selectcard")
Run Code Online (Sandbox Code Playgroud)

这是完整的代码

function validate()
{
 var ddl = document.getElementById("cardtype");
 var selectedValue = ddl.options[ddl.selectedIndex].value;
    if (selectedValue == "selectcard")
   {
    alert("Please select a card type");
   }
}
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示


Ash*_*pra 6

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>
Run Code Online (Sandbox Code Playgroud)


jon*_*ana 6

您可以使用该属性检查所选值的索引是 0 还是 -1 selectedIndex

在您的情况下 0 也不是有效的索引值,因为它是“占位符”:
<option value="selectcard">--- Please select ---</option>

现场演示

function Validate()
 {
   var combo = document.getElementById("cardtype");
   if(combo.selectedIndex <=0)
    {
      alert("Please Select Valid Value");
    }
 }
Run Code Online (Sandbox Code Playgroud)