简体   繁体   中英

How to update multiple form elements with ajax call

I need to update the form divs after an ajax was successfully called via jQuery. There're some form elements on my page. And I'd like to fill it with the values sent back from ajax call. Which is in json format.

While #inst_name is an input[type=text] in which doing 2 things.

  1. As an autocomplete input via jquery autocomplete.
  2. As a name reference for mysql query in this script.

HTML :

<input type="text" name="inst_name" id="inst_name" />


<form method="post" action="">
<textarea name="inst_addr" id="inst_addr"></textarea>
<select name="inst_prov" id="inst_prov">
<option value="1">Bangkok</option>
<option value="2">Chiang Mai</option>
<option value="3">Samui</option>
<option value="4">Phuket</option>
</select>



<input type="text" name="inst_tel" id="inst_tel" />
<input type="text" name="inst_fax" id="inst_fax" />


<label><input type="radio" name="inst_dep" id="inst_dep1" value="1" />Dep 1</label>
<label><input type="radio" name="inst_dep" id="inst_dep2" value="2" />Dep 2</label>
<label><input type="radio" name="inst_dep" id="inst_dep3" value="3" />Dep 3</label>
</form>

jQuery :

$('#inst_name').keyDown(function(){
    $.ajax({
        url: 'inc/form_institute.json.php',
        dataType:'json',
        data: {name:$('#inst_name').val()},
        success: function(data){
            $('#inst_addr').html(data.addr);
            $('#inst_prov').val(data.prov);
            $('#inst_zip').val(data.zip);
            $('#inst_tel').val(data.tel);
            $('#inst_fax').val(data.fax);
            $('#inst_dep').val(data.dep);
        }
    });
});

JSON :

{
"addr":"123/4 Kitty Ave.",
"prov":"80",
"zip":"12345",
"tel":"0753245675",
"fax":"075123456",
"dep":"2"
}

Try using:

$(document).on("keyup", "#inst_name", function(){
    //you're ajax here
}

That way the more you type the more specific the response will be.

Good luck :)

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