I have a working jQuery solution for inserting city based on a Norwegian 4 digit zipcode in a form. But there is two sets of addresses in this form, and I do not know how to duplicate, rename or merge the jQuery function.
<form>
<!--address1-->
<input type="text" name="ZIPCODE" id="USER.ZIPCODE" size="4" maxlength="8" />
<input type="text" name="CITY" id="USER.CITY" size="30" maxlength="100" value="test" />
<!--address2-->
<input type="text" name="ZIPCODE2" id="USER.ZIPCODE2" size="4" maxlength="8" />
<input type="text" name="CITY2" id="USER.CITY2" size="30" maxlength="100" value="test" />
<script type="text/javascript">
$(function(){
$inputField = $("#USER\\.ZIPCODE");
$outputField = $("#USER\\.CITY");
$inputField.keyup(function(){
if($inputField.val().match(/\d{4}/)) {
$.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code="+$inputField.val()+"&callback=?",
function(data){
$outputField.val( data["postal_codes"][0]["city"] );
$("#USER\\.CITY").attr('readonly','readonly');
});
} else {
$outputField.val("?");
}
});
});
$(function(){
$inputField = $("#USER\\.ZIPCODE2");
$outputField = $("#USER\\.CITY2");
$inputField.keyup(function(){
if($inputField.val().match(/\d{4}/)) {
$.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code="+$inputField.val()+"&callback=?",
function(data){
$outputField.val( data["postal_codes"][0]["city"] );
$("#USER\\.CITY2").attr('readonly','readonly');
});
} else {
$outputField.val("?");
}
});
});
</script>
</form>
I have looked through lots of posts here about merging jQuery functions and func1 func2 approaches without geting the grip on this. I guess it could also be merged with an if-statement of some kind. Working example single address: http://jsfiddle.net/Rx4jZ/ (Both attr and prop will probably work)