Reputation: 18929
I have a small jQuery function which I am using to capture the input of a text field as zipcode and then grab some relevant data from the db (snow fall and wind speed).
The function:
$(document).ready(function(){
var zip = $('#id_zipcode');
zip.change(function() {
function updateEvnFactors(){
var selected = zip.val();
if (selected) {
$.getJSON(get_zip_factors_url, {zipcode: selected}, function(env_data, jqXHR){
$('#snow_fall').html(env_data[0].snow);
$('#wind_speed').html(env_data[0].wind);
});
}
}
updateEvnFactors();
$('#id_zipcode').keyup(updateEvnFactors);
});
});
Where the element #id_zipcode
is a text input. This works in a rudimentary way, but the html elements #snow_fall
and #wind_speed
are only updated when the user tabs onto another form field or clicks somewhere outside of the #zip_code
input.
What am I missing to make the html elements update as soon as there are valid values returned from the ajax call (i.e. a valid zipcode passed).
As a bonus question - how can I limit my ajax to only being activated when there are >=5 digits in the input field?
Any help will be much appreciated.
Upvotes: 0
Views: 1157
Reputation: 150263
As a bonus question - how can I limit my ajax to only being activated when there are >=5 digits in the input field?
if (selected.length >= 5)
Now regarding the main question, you subscribed for the onchange
event, it fires only on a change + blur(lose focus). this is what the spec says.
You can change to:
$('#id_zipcode').keyup(function() {
var selected = this.value;
if (selected.length >= 5) {
$.getJSON(get_zip_factors_url, {
zipcode: selected
}, function(env_data, jqXHR) {
$('#snow_fall').html(env_data[0].snow);
$('#wind_speed').html(env_data[0].wind);
});
}
}).keyup();
Upvotes: 1
Reputation: 14479
I believe the onchange
event only fires once the field has lost focus. I think your code should look more like this:
$(document).ready(function() {
$('#id_zipcode').keyup(function() {
if ($(this).val().length >= 5) {
$.getJSON(get_zip_factors_url, {zipcode: selected}, function(env_data, jqXHR) {
$('#snow_fall').html(env_data[0].snow);
$('#wind_speed').html(env_data[0].wind);
});
}
});
});
Upvotes: 0