postnr => by

by khebbie

HTML

<script src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
<form  id="addressForm" method="get" action="">
<fieldset>
<p>
    <label for="postnr">Postnr: </label> 
    <em>  </em><input id="postnr" type="text" class="required" minlength="4" size="4"/>
</p>
<p>
    <label for="by">By: </label>  
    <em>  </em><input id="by" type="text"  READONLY/>
</p>
<p>
     <input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>

CSS

* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }

JavaScript

$('#postnr').change(function() {
    if($('#postnr').val().length != 4) {
    return;
    }
    $.ajax({
        url: "http://geo.oiorest.dk/postnumre/" + $('#postnr').val() + ".json",
        dataType: "jsonp",
        success: function(postdistrikt) {
            $("#by").val(postdistrikt.navn);
        }
    });
});
$(document).ready(function() {
    $("#addressForm").validate();

    $.ajax({
        url: "http://geo.oiorest.dk/postnumre.json",
        dataType: "jsonp",
        success: function(postdistrikter) {
            var arr = $.map(postdistrikter, function(postdistrikt) {
                
                return postdistrikt.nr;
            });
            $("#postnr").autocomplete({
                source: arr
            });
        }
    });


});