Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"); } 
like image 986
littledevils326 Avatar asked Apr 13 '13 11:04

littledevils326


People also ask

How do you check whether a dropdown is selected or not?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} .

How do you validate a drop-down list in HTML?

Validate (Check) HTML Select DropDownList using jQuery Inside the jQuery OnClick event handler, the HTML Select DropDownList object is referenced and if the selected value matches the value of the default item then an error message is displayed using JavaScript alert message box.

Which event is called on selection of an item from a dropdown list?

The HTML Select DropDownList has been assigned a jQuery OnChange event handler. When an item is selected in the HTML Select DropDownList, the jQuery OnChange event handler is executed within which the Text and Value of the selected item is fetched and displayed in JavaScript alert message box.


1 Answers

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

like image 105
Sachin Avatar answered Nov 13 '22 04:11

Sachin