0

I post a form with $.post on the keyup of a input type='text', the problem is that after the post, I click anywhere in the browser (even on the firebug console) an the $.post is going to be repeated

live link: http://mrgsp.md:8080/awesome/lookupdemo

(click on a button to open a popup, after search for a letter e.g. 'm' after click on something [watch the firebug console] )

my script is something like this:

$('#theform input:text').keyup(function (e) {
        var w = e.which;
        if (w < 9 || w > 45 && w < 91 || w > 93 && w < 112 || w > 185)
            $('#theform').submit();
    });

$('#theform input:hidden').change(function () {
    $('#theform').submit();
});

$('#theform').submit(function(e){
    e.preventDefault(); 
...
 $.post(...);
});

UPDATE: just noticed that without the $('#theform input:hidden').change(... all is ok

UPDATE 2: apparently the textbox also triggers change, strange cuz i registered the change for input:hidden not for input:text

UPDATE 3: solved, it looks like I should have used input[type='hidden'] instead of input:hidden

Omu
  • 69,856
  • 92
  • 277
  • 407

1 Answers1

2

In some browsers, the change event (only?) fires when the input in question loses focus - that's why you're seeing another post when you click elsewhere on the page. See this question for more on that - it's about radio buttons, but the change/unfocus behaviour is similar.

And as for why the textbox got bound to the change event: The :hidden selector does a few more things than just selecting inputs with the type hidden. In this case, the text input wasn't visible on the page when your script ran, so it got selected too ('cause it was hidden!).

If you only want "true" hidden inputs to be selected, you'll want the somewhat uglier selector $('#theForm input[type=hidden]').

Hope this helps!

PS: Changing the value of an input with JS won't trigger the change event. Since an input of type hidden is presumably only changeable via JS, you should probably just call $('#theForm').submit() from wherever you change the hidden value.

Community
  • 1
  • 1
Xavier Holt
  • 14,471
  • 4
  • 43
  • 56