views:

82

answers:

4

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;          
    }
+6  A: 

document.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"

Pandiya Chendur
A: 

Hi there

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 compare to your ==.

I hope this helps.

It is in a different function.
RPK
+4  A: 
var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")
Tubbe
This might not be the "best" solution, but the code can be copy/pasted and ready to use.
Tubbe
A: 

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>

Satya