[javascript] Validate select box

I'm using the jQuery plugin Validation to validate a form. I have a select list looking like this:

<select id="select">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

Now, I want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?

This question is related to javascript jquery html validation forms

The answer is


Perhaps there is a shorter way but this works for me.

<script language='JavaScript' type='text/javascript'>
    function validateThisFrom(thisForm) {
        if (thisForm.FIELDNAME.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME.focus();
            return false;
        }
        if (thisForm.FIELDNAME2.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME2.focus();
            return false;
        }
    }
</script>
<form onSubmit="return validateThisFrom (this);">
    <select name="FIELDNAME" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
    <select name="FIELDNAME2" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
</form>

if (select == "") {
    alert("Please select a selection");
    return false;

That should work for you. It just did for me.


I don't know how was the plugin the time the question was asked (2009), but I faced the same problem today and solved it this way:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option as suggested by Jeremy Visser or set value=""

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

Obs: redsquare's solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Hope it helps! :)


   <script type="text/JavaScript">  
function validate() 
{
if( document.form1.quali.value == "-1" )
   {
     alert( "Please select qualification!" );
     return false;
   }
}

</script>
<form name="form1" method="post" action="" onsubmit="return validate(this);">
<select name="quali" id="quali" ">
        <option value="-1" selected="selected">select</option>
        <option value="1">Graduate</option>
        <option value="2">Post Graduate</option>
      </select> 
</form>





// this code works 110% tested by me after many complex jquery method validation but it is simple javascript method plz try this if u fail in drop down required validation//

<select id='bookcategory' class="form-control" required="">
                    <option value="" disabled="disabled">Category</option>
                    <option value="1">LITERATURE & FICTION</option>
                    <option value="2">NON FICTION</option>
                    <option value="3">ACADEMIC</option>
            <option value="4">CHILDREN & TEENS</option>

                </select>

HTML form validation can be performed automatically by the browser. Try the above code:
The rest all will be done automatically, no need to create any js functions just this dropdown and a submit button.


you want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?

You can do this by simple adding attribute required = "required" in the select tag. you can see it in below code

<select id="select" required="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

It worked fine for me at chorme, firefox and internet explorer. Thanks


For starters, you can "disable" the option from being selected accidentally by users:

<option value="" disabled="disabled">Choose an option</option>

Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:

select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
  // value is set to a valid option, so submit form
  return true;
}
return false;

Or something to that effect.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"