开发者

Having a form submit on every keypress

I have a currency calculator that requires buttons to convert to/from currencies. I'd like to make it so that it converts (runs the form) as soon as anything is typed in. Currently, my jQuery that handles the button click looks like this (this is one of two click handlers):

        $('#convertFromButton').click(function() {
           开发者_运维百科 $("#currencySelectValue2").val($("#currencySelect").val());
            $("#btcValueForm").val($("#btcValue").val());
            $.post("php/convertFromForm.php", $("#convertFromForm").serialize(), function(data){ 
                $('#fromCurrencyValue').removeClass('intra-field-label');
                $('#fromCurrencyValue').val(data);
            });
        });

The first text field is #fromCurrencyValue and the 2nd one is #btcValue.

How can I get it to work in the manner I described?


I would do

$('#formCurrencyValue, #btcValue').keyup(function() {$('#convertFromButton').click(); });

then if you change any of your submit logic, it'll change for all events

I switched it to keyup. This should register for every key pressed.


I'm going to differ from the others and say that explicitly calling event handlers from other functions/events is a dirty practice that should be avoided. You can be much more clear by doing the following:

    var xhr;
    function refresh() {
        $("#currencySelectValue2").val($("#currencySelect").val());
        $("#btcValueForm").val($("#btcValue").val());
        if(xhr) xhr.abort();
        xhr = $.post("php/convertFromForm.php", $("#convertFromForm").serialize(), function(data){ 
            $('#fromCurrencyValue').removeClass('intra-field-label').val(data);
        });
    }

    //Bind as many things as you want to your new function.  Also easily unit tested!  Yay!
    $('#convertFromButton').click(refresh);
    $('#fromCurrencyValue, #btcValue').keyup(refresh)


// if you keyup in fromCurrencyValue or btcValue it will trigger the click on convertFromButton
$("#fromCurrencyValue, #btcValue").bind("keyup", function() {
  $('#convertFromButton').click();
});

But keep in mind that $.post is by default async, so if one request asked later is answer before the other, you will have unwanted behavior.

Edit

When posting the value use this:

var xhr; // make it global

/*
  Your code goes here
*/
if (xhr)
  xhr.abort(); // if there's a xhr request abort it

xhr = $.post(...)
/*
  The rest of your code
*/

So you wont get the unwanted behavior :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜