2

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?

2
  • It's interesting. What happens if you then return back to the first field? Should it append one more time? Commented Mar 13, 2013 at 5:26
  • You want location to be address + city + state + zip? Commented Mar 13, 2013 at 5:29

4 Answers 4

1

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');
    }
});

http://jsfiddle.net/J6G9f/1/

Script also correctly handles removing parts of the address and it automatically updates the result.

Sign up to request clarification or add additional context in comments.

Comments

0

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

for some reason, typing in street i end up with streetstreetstreet
0

You can use the native value like this:

$('#location')[0].value += this.value;

2 Comments

how do I add this solution?
You just have to replace the line where you set the value.
0

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

1 Comment

confused on how to implement this solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.