Split a text field in half with Javascript, validate it, and then merge it again

advertisements

A client is asking that a textfield containing phone-number data be split into two -- one for country code, the other for the rest of the number.

Alas, this field is pretty hard-coded into the system and all data collected thus far has been as one consolidated field (and thus saved as one column in the database).

I'm thus thinking the best answer might be to do the following:

  1. Using Javascript, replace the single text field with two text fields.
  2. These then become merged back into the original text field when the user clicks the submit button.
  3. Bonus marks if there's a way to separate that field back into two again when it's read from the database (I.e., when an administrator views the entry). Note that the data format must be consistent -- I don't want to mix the existing string data with, say, a bunch of JSON strings.

Is this the best way to go about this? Are there any foreseeable problems (beyond the user not having JavaScript enabled) with this approach? Is there a jQuery plugin that's designed to do stuff like this?

I also need to validate it as a valid phone number at some point, but I can figure that out myself.


If you dont want to use a plugin you can always check out this snippet I made on jsFiddle

If you want to make sure it works in the JS just change the display:'none' to display:'block'

here is my JavaScript

$(function() {
    $('#phone').css({ display:'none' });
    $('#phone').after(') <input type="text" name="phoneMainNumber" id="phoneMainNumber" />').after('(<input type="text" value="555" name="phoneAreaCode" id="phoneAreaCode" style="width:30px;" />');
    bindChange();
});

function bindChange() {
    $('#phone').val('('+$('#phoneAreaCode').val()+') ');
    $('#phoneMainNumber, #phoneAreaCode').keyup(function() {
       $('#phone').val('('+$('#phoneAreaCode').val()+') '+$('#phoneMainNumber').val());
    });
}