views:

815

answers:

2

I have an "Add Person" form with a few fields (name, address, phone number, etc).

I want to be able to pre-fill some of the fields using information from other fields BEFORE submitting the form. For example, once the user puts in a city, an Ajax query will pull the area-code for the phone number (the Controller has a "city to area code" database) and put it in the phone number field, hoping it will save some typing.

I've tried using observeField, but it seems like it can only change the innerHTML of an element, not the value of an input field.

Any suggestions of how to go about? Thanks.

+1  A: 

If you want to change the value on a text input, then you can use .val()

So in your ajax success you will have a callback:

success: function(data){
  $('#foo').val(data);
}
Colin
+1  A: 

Assume you have two forms:

<form id="formOriginal">
    <input type="text" name="name"/>
    <input type="text" name="address"/>
    <input type="text" name="city"/>
    <input type="text" name="state"/>
</form>

<form id="formCopy">
    <input type="text" name="name"/>
    <input type="text" name="address"/>
    <input type="text" name="city"/>
    <input type="text" name="state"/>
</form>

You should be able to loop through the items and copy values as follows:

$('#formOriginal input').each(function(e) {
    var name = e.attr('name');
    var $copy = $('#formCopy input[@name=' + name + ']');

    if ($copy) {
        $copy.val($(e).val());
    }
});
Matt Huggins