javascript dropdown condition

I have the following dropdown. Client wants to form throw an error if the value fail is selected. I told him easy solution is to remove the fail from the menu :) That way only option is Pass and the problem is solved:) Not really. He still wants both options and if Fail selected he wants to see the required error may be a text saying you need to select Pass.

               <div class="section colm colm6">
                  <label class="field select">
                      <select id="cond" name="Cond" required>
                           <option value=''>Condition</option>
                           <option value='Pass' >Pass</option>
                           <option value='Fail' >Fail</option>
                        </select>
                          <i class="arrow double"></i>                             
                  </label>
               </div> 

I need to do the error check as soon as the file is selected rather than until the whole form is submitted. I have another 2 fail and pass dropdowns and 2 yes and no dropdowns that I need to do the same thing. If I get one working I should be able to the others (I hope)

I am guessing that I need to create a some sort of function similar to

  function checkCategory(){
        if(document.getElementById('cond').value === 'Fail') {
           alert("Client says you need to enter Pass");
   return false;
   }
  }

and may be use an onselect ( I am not sure how to call it ) use onselect="javascript:checkCategory();"

I am pretty much stuck at this point. Your help is much appreciated. Thank you for your time.

Answers 1

  • Its easy to do this using jquery, just use its .change() event handler as follows:

    $(function() {
        $('#cond').change(function() {
        if(this.value === 'Fail') {
            alert('Please Select Pass');
        }
      })
    })
    

    This will solve your problem. Check this jsFiddle: https://jsfiddle.net/mayank_shubham/9d3dcd07/

    You can also do this in javascript by using an onchange event handler in your select menu as:

    <script>
    
    function checkCategory() {
        if(document.getElementById('cond').value === 'Fail') {
        alert('Please Select Pass');
      }
      return false;
    }
    
    </script>
    <div class="section colm colm6">
        <label class="field select">
            <select id="cond" name="Cond" onchange = "checkCategory()"required>
                 <option value=''>Condition</option>
                 <option value='Pass' >Pass</option>
                 <option value='Fail' >Fail</option>
              </select>
                <i class="arrow double"></i>                             
        </label>
     </div> 
    

    See a working demo


Related Articles