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"); }
Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With