Home > Blockchain >  .submit() does not act as pressing the submit button
.submit() does not act as pressing the submit button

Time:07-11

I have a form.
When I exit the text field it should alert "HH" and submit the form - run a PHP script.
if I exit the text field, I get the alert but it is not submitted.
only pressing the submit button calls the PHP script.
what I'm doing wrong?
I found a few questions as my, tried the solution, but it not working.

    <html>
      <head>
       <script src="vendor/jquery/jquery-3.2.1.min.js"></script>
       <script>
          $(document).ready(function(){
          $("#faults_form input").blur(function(){
            alert("HH");
            $("#faults_form").submit();
            return false;
          });
        });

   </script>
    
  </head>



<body>
    <form id="faults_form" name="faults_form" action="/index.php" method="post" enctype="multipart/form-data">
    
    <label for="name">Enter server name:</label>
    
    <input type="text" name="name" value="" >
    <input type="submit" name="submit" value="Submit">
    </form>
 </body>
</html>

CodePudding user response:

It sounds like your server-side script relies on seeing the value from the submit button. When you submit a form with a submit button, the name and value of the submit button are included in the form (in your case, submit=Submit). That does not happen when you submit the form programmatically, because the button wasn't clicked (there could be multiple submit buttons, after all, with different meanings).

To include the value, you can either use code to it to the form being submitted, or click the button programmatically instead:

$("#faults_form input[type=submit][value=Submit]").click(); 

That will include the submit=Submit in the form.


A couple of side notes for what they're worth:

  • I wouldn't use alert in relation to blur/focus events or similar. alert messes with focus in weird ways that vary from browser to browser. (For instance, on Chromium-based browsers, your code cause an infinite loop of alerts.)

  • I wouldn't submit a form when focus leaves a text field. That's very unusual and therefore surprising behavior. As a user, it would bother me quite a bit and make me not trust other things in the page/app to behave normally.

  • Related