Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change an input field before submit

Tags:

jquery

I have to encode a domain name (IDNA) for a particular registrar using accents.

I have a simple input field :

<input type="text" id="idndomain" name="sld[0]" size="40" />

My jQuery function

$(document).ready(function() { 
    $('#domainform').submit(function(){
        $.getJSON("includes/idna/idna.php", {
            domain: $("input#idndomain").val()
        }, function(data){
            $("div#result").html($('<b>' + data.encoded + '</b>'));
            $('#idndomain').val(data.encoded);
        });
        return true;
    });
}); 

So i'm sending a query to idna.php which encodes the domain name and returns a json array :

{"encoded":"xn--caf-dma.ch"}

Problem is that the form is being submited with the 'original' value, not the value returned by the json query.

Question is : how to 'wait' for json result first, replace the input field with the encoded string and them submit ?

like image 778
Disco Avatar asked Nov 02 '09 11:11

Disco


1 Answers

Try binding to the submit button instead of the form, and explicitly invoke the form's submit handler within the json call's success callback:

    $(document).ready(function() { 
            $('#submitButton').click(function(){

                    // maybe disable the submit button once clicked?
                    $(this).attr('disabled', true); 
                    $.getJSON("includes/idna/idna.php", {
                            domain: $("input#idndomain").val()
                    }, function(data){
                            $("div#result").html($('<b>' + data.encoded + '</b>'));
                            $('#idndomain').val(data.encoded);
                            // now submit the form
                            $('#domainform').submit();
                    });
                    return false;
            });
    });
like image 98
karim79 Avatar answered Sep 28 '22 22:09

karim79