Ryan Sisson
Ryan Sisson

Reputation: 139

Validating a select box

I was wondering how I go about validating that a user picked a country from the select box that I have coded.

The code:

<label>Select a Country:
    <br />
    <select name="country">
        <option selected disabled>Choose a Country</option>
        <option value="United States">United States</option>
        <option value="Canada">Canada</option>
        <option value="Mexico">Mexico</option>
    </select>
</label>

Would the function look anything like:

function validateCountry(){
    if (form.country.value=="")
        alert("Please Select a Country!");
        form.country.focus();
        return false;
}

Upvotes: 0

Views: 61

Answers (3)

techy-coder
techy-coder

Reputation: 83

Can Also Validate based on document.getElementById, just add the code, id="country" in select box,

 <label>Select a Country:
  <br />
 <select name="country" id="country">
   <option value="">Choose a Country</option>
   <option value="United States">United States</option>
   <option value="Canada">Canada</option>
   <option value="Mexico">Mexico</option>
  </select>
</label>
 <button id='submit' onclick="return validateCountry();">Validate</button>
function validateCountry() {
 if(document.getElementById('country').value =='')
   {
     alert("Please select a country");
      return false;
   } 
  else
   {
      return true;
    } 
}

Upvotes: 0

George
George

Reputation: 36786

  • Your <select> element will currently have a default value of "Choose a Country" so your if statement will never be true (there is no option with a value == ''). Set the value attribute to change that.
  • form isn't defined. You can select your form with a variety of methods, one option being document.querySelector(). The following assumes that the subject <select> box is the first matching select[name="country"] in your document.

function validateCountry(){
    var selectBox = document.querySelector('select[name="country"]');
    if (selectBox.value==""){    
        alert("Please Select a Country!");
        selectBox.focus();
        return false;
    }
}

document.getElementById('button').onclick = validateCountry;
<label>Select a Country:
    <br />
    <select name="country">
        <option value='' selected disabled>Choose a Country</option>
        <option value="United States">United States</option>
        <option value="Canada">Canada</option>
        <option value="Mexico">Mexico</option>
    </select>
</label>

<button id='button'>Validate</button>

Upvotes: 3

Rahul Sharma
Rahul Sharma

Reputation: 453

 if( document.myForm.Country.value == "-1" )
   {
     alert( "Please provide your country!" );
     return false;
   }

Upvotes: 0

Related Questions