return false is not working

前端 未结 2 559
旧时难觅i
旧时难觅i 2021-01-27 09:25

I have created one form with dynamically created check box\'s . And i have used one j query script that will check weather user has checked at-least one check box or not .Tf it

相关标签:
2条回答
  • 2021-01-27 09:32

    If you are going to return false from an event handler function, then you need to do it from the event hander itself, and not just another function that it calls.

    Your onclick function doesn't have a return statement. It calls Validate and then does nothing with the value that function returns.

    onclick="return Validate();"
    

    Convention reserves variable names starting with capital letters for constructor functions. Call your function validate, not Validate.

    It is generally a better idea to handle this kind of test when the form is submitted rather than when a particular submit button is clicked.

    Modern JavaScript doesn't use onclick/onsubmit/etc attributes. We use addEventListener instead.

    function validate(event) {
        // Your logic
        if (someCondition) {
            // Stop
            event.preventDefault();
        }
    }
    
    document.querySelector("form").addEventListener('submit', validate);
    
    0 讨论(0)
  • 2021-01-27 09:53

    Try this code:

    Add class to check box

    print "<td><input type=\"checkbox\" class="mycheckbox" name=\"dptid$i\" value=\"$row[dpt_id]\"></td>\n";
    

    jQuery function:

    function Validate() {
      var counter=0;
    
      $( ".mycheckbox" ).each(function() {
        if($(this).is(':checked'))
        {
          counter++
        }
      });
    
      if (counter == 0)
      {
        alert("You have not selected an item to delete");
        return false;
      }
      else
      {
        alert("Are you sure you want to delete  "+counter+" records");
      }
    }
    
    0 讨论(0)
提交回复
热议问题