skip to Main Content

I have a series of select boxes all with a class value = "topic". I want to submit the form only if one or more boxes have a selected value. My code detects if any of the select boxes have a selected value or not but the form submits either way. Just wondering how to stop the form from submitting?

<select name="Topic_ACH" id="ddlTopic_ACH" class="topic">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select> 

<select name="Topic_Bankruptcy" id="ddlTopic_Bankruptcy" class="topic">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>

etc.

//At least one Topic checkbox must be checked to submit the form             
 $('#MainContent_btnUpdateSample').click(function (e) {
 var anySelected = false;
 $(".topic option:selected").each(function () {
     if (!$(this).val() == "") {
         anySelected = true;
     }
 });
 if (!anySelected) {
     alert("You must select at least one topic");
     e.preventDefault();
     return false;                    
 }
 }); 

2

Answers


  1. You probably should use the submit event on the form element instead of the click event on the form button. Try out the following:

    document.querySelector('form#some-form').addEventListener('submit',  function(e) {
        e.preventDefault();
        return false;
    });
    

    In combination, you might find merit in the required attribute for your <select> elements since that simplifies your logic greatly (adding this element requires the user to select a value; if nothing is selected the browser will automatically display any error messages).

    (Also you don’t need jQuery)

    Login or Signup to reply.
  2. You can have something like this,

    <input type='submit' id='MainContent_btnUpdateSample' onclick='return handleSelect()' />
    
    
    function handleSelect() {
     var anySelected = false;
     $(".topic option:selected").each(function () {
         if (!$(this).val() == "") {
             anySelected = true;
         }
      }
    
     if (!anySelected) {
         alert("You must select at least one topic");
     }
    
     return anySelected;
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search