I have a HTML dropdown control. I want to check that if the text in it is "Select", it must display error message. I am using following code to do this, but it is not working.
if (document.getElementById("StudentCountry").value == "Select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
I have a HTML dropdown control. I want to check that if the text in it is "Select", it must display error message. I am using following code to do this, but it is not working.
if (document.getElementById("StudentCountry").value == "Select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
Share
Improve this question
asked Dec 16, 2009 at 12:15
RKhRKh
14.2k52 gold badges159 silver badges279 bronze badges
1
- 1 Would you please post the HTML/PHP/Whatever code? – Zeemee Commented Dec 16, 2009 at 12:17
4 Answers
Reset to default 5document.GetElementById("StudentCountry").SelectedIndex=0;
or
function getDropDownListvalue()
{
var IndexValue = document.GetElementById("StudentCountry").selectedIndex;
var SelectedVal = document.GetElementById("StudentCountry").options[IndexValue].value;
alert(SelectedVal);
}
check for selected value="select"
var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")
How is this javascript code embedded in your html file? Is it just inside a script element and not in a distinct function? If so, this will probably always return null for the function, as the dropdown is not loaded at the moment it is used. Otherwise the code should work. Just put in a function, let's say checkCountry() and add it as onchange="checkCountry();" to the tag. The second thing that could break your code is the check for the "Select" text. If you check for value on an option, it will most likely check for the value attribute, such as: Select And in this example select is written all lowercase, which would not pare to your ==.
I hope this helps.
Your code seems to be perfect .check onceagain Default options values is "select" or not..
<html>
<head>
<script language="javascript">
function validate(){
alert('ddddddddddd ='+document.getElementById("StudentCountry").value);
if (document.getElementById("StudentCountry").value == "select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
return false;
}
</script>
</head>
<body>
<select id="StudentCountry">
<option value="select" >---------Please Select ---------</option>
<option value="India" >India</option>
<option value="USA" >UAS</option>
<option value="UK" >UK </option>
</select>
<a onclick="javascript:validate();" href="#">click here to validate</a>