I'm trying to populate a field with Street Address, City, State, and Zip but right now when I enter data into each field it replaces the last one.
$("#trainer_address").keyup( function () {
$('#location').val($(this).val());
});
$("#trainer_city").keyup( function () {
$('#location').val($(this).val());
});
$("#trainer_state").keyup( function () {
$('#location').val($(this).val());
});
$("#trainer_zip").keyup( function () {
$('#location').val($(this).val());
});
How do I get it to keep the previous value, and then add the next so I can end up with something like 402 StreetAddress City State, 12345?
-
It's interesting. What happens if you then return back to the first field? Should it append one more time?dfsq– dfsq2013年03月13日 05:26:21 +00:00Commented Mar 13, 2013 at 5:26
-
You want location to be address + city + state + zip?Bemmu– Bemmu2013年03月13日 05:29:54 +00:00Commented Mar 13, 2013 at 5:29
4 Answers 4
This script will do it:
var $loc = $('#location'),
address = [],
getAddress = function() {
var str = address.slice(0, 3).join(' ') + ', ' + (address[3] || '');
return str.replace(/\s+/g, ' ').replace(/,\s$/, '');
}
$("#trainer_address, #trainer_city, #trainer_state, #trainer_zip").on({
focus: function() {
$loc.val(getAddress());
},
keyup: function() {
address[$(this).index()] = $(this).val();
$(this).trigger('focus');
}
});
Script also correctly handles removing parts of the address and it automatically updates the result.
Comments
concatenate the old val with new val using + operator...and you can avoid multiple keyup function using multiple selector....
try this
$("#trainer_address,#trainer_city,#trainer_state,#trainer_zip").keyup( function () {
var location=$('#location').val();
$('#location').val(location + $(this).val());
});
1 Comment
street i end up with streetstreetstreetYou can use the native value like this:
$('#location')[0].value += this.value;
That's because you're overwriting it. Try concatenating:
$('#location').val($('#location').val() + $(this).val());
For example, change this:
$("#trainer_zip").keyup( function () {
$('#location').val($(this).val());
});
to this:
$("#trainer_zip").keyup( function () {
$('#location').val($('#location').val() + $(this).val());
});
Do that for each keyup() event function