Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - How to check if an item is selected from an HTML drop down list?

I have a drop drown list and I am having trouble checking whether or not a value has been selected from the drop down list

Below is my HTML Code :

<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/>

Below is my JavaScript Code :

var card = document.getElementByName("cards")[0].value;
if (card.value == selectcard) {
    alert("Please select a card type");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well you missed quotation mark around your string selectcard it should be "selectcard"

if (card.value == selectcard)

should be

if (card.value == "selectcard")

Here is complete code for that

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

JS Fiddle Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

56.9k users

...