开发者

setTimeout on form submission returning 'not a function' error

开发者 https://www.devze.com 2023-01-20 04:07 出处:网络
I h开发者_如何学运维ave the following: var thiscode = { init: function(){ jQuery(\'#submit\').bind(\'click\',thiscode.clickListener);

I h开发者_如何学运维ave the following:

var thiscode = {
init: function(){
    jQuery('#submit').bind('click',thiscode.clickListener);
},

clickListener: function(event){
    setTimeout('document.myform.submit()',5000);
    return false;
}
};
thiscode.init();

setTimeout is working, but when it fires, I get this: "document.myform.submit is not a function".

Any idea why, and/or how to fix it?


This likely has nothing to do with your use of setTimeout (which has issues raised by other people).

The most likely cause is that you have an element named submit (or with that as an id) inside the form (probably the one that you are matching with your jQuery selector) and that this has replaced the function that was on the submit property with an HTMLElementNode.

The easiest solution is to rename the element.


Don't pass a string to setTimeout, pass an anonymous function...

clickListener: function(event) {
  setTimeout(function() {
    document.myform.submit();
  }, 5000);
  return false;
}

EDIT: Just had a revelation. If you have an element in your form with a name/id of "submit", that will override the submit function in the DOM (document.myform.submit will now refer to that element instead of the function). If this is the case, you'll need to rename that element.


setTimeout can also take a function handle - try passing document.myform.submit without the quotes:

setTimeout(document.myform.submit,5000);


David's answer is good, but you really should not be binding click, what if the user presses enter to submit the form? They've just gone around your procedure.

Instead bind .submit(). You can use a variable to control if there is a submit:

var submitNow = false;
$(function() {  
      // Set up the submit handler
    $("form").submit(function() {

          // In 5 seconds...
        setTimeout(function() {

              // Set the submit variable to true
            submitNow = true;

              // Trigger the submit
            $("form").submit();
        }, 5000);

          // This will only submit if submit variable is true.
        return submitNow;
    });
});​

Try it out with this jsFiddle example

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号