简体   繁体   中英

Disable a submit input from submitting a form jquery

I am implementing a password manager like chrome extension, which detect the password field and try to intercept the submit function. What I would like is:

  1. User click "login" in a website (say Facebook). The extension content script detect the value of password and username
  2. Ask if the user would like to store the login credentials in the manager
  3. If yes, store the credentials.

The problem is in step 2, I was trying to prevent it from submitting until the dialog returns user action, just like any other browser built-in password manager. But apparently the preventDefault() does not work because the webpage keeps refreshing just like calling curSubmit[0].click(), which would make the dialog keep reappearing.

Is there any idea what is wrong? Part of my code is:

var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
  if (inputs[i].type.toLowerCase() === "password") {
    var curSubmit = $("input[type=submit]",inputs[i].closest('form'));
    curSubmit[0].click(function(event){
      event.preventDefault();
    });

    curSubmit[0].onclick = function(){
       $('body').append('<div id="store-dialog" title="Store password?"><p>Do you want to store the login credentials?</p></div>');
       var buttons = $( ".store-dialog" ).dialog( "option", "buttons" );
       $( "#store-dialog" ).dialog({
          resizable: false,
          height: "auto",
          position: { my: "center", at: "center", of: window },
          modal: true,
          buttons: {
            "Yes": function() {
              $( this ).dialog( "close" );
            },
            "Not this time": function() {
              $( this ).dialog( "close" );
            },
            "Never": function() {
              $( this ).dialog( "close" );
            }
          }
      });
    }
  }
  break;
}

The syntax you're using for the click handler is invalid because curSubmit[0] is not a jQuery object but a standard DOM element.

These are correct:

  • curSubmit[0].onclick = function(e) { ...... };
  • curSubmit[0].addEventListener("click", function(e) { ...... });

As for stopping try the entire artillery for both click and submit events:

event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM