Search code examples
jqueryphone-number

jquery add more form items


So here is my question, what I am wanting is to allow our sales guys to add more phone numbers in a customers contact.

We have a a form which looks like this. (note I only showing the part from our contact area)

<form>
<div id="numbers">
<input id="no1" value="" class="phone" type="numbers"/>
</div>
</form>

so basically what I want is away that when they complete one phone number it adds a new input box below it and ask if any more they want to add.

I then need to work out the best way to store them, any suggestions?

My thinking was to join them together as the following

025555555,0311555445,044585522

Solution

    1. You need a name on that field or the form won't submit it with the post. Only inputs with names get submitted. Unless, of course, you're submitting via AJAX and constructing the post data yourself.
    2. Don't store the data as comma-separated values. Keep a separate table for phone numbers and use a one-to-many relationship between the person and their phone numbers. Normalized data is (almost) always the right way to go.
    3. Do you really need unlimited phone numbers? Or would some small, fixed number suffice? Say, phone, alternate phone, and cell? If 3 would do, why not just create the three text boxes and make the latter two optional?
    4. You can use something like the following:

    Example:

    $(function() {
         $(document).on('blur','[name="phone"]', function() {
             var $phones = $('[name="phone"]'),
                 empty = $phones.filter( function() { return !$(this).val(); } ).length;
             if (empty == 0) { // don't add a new one unless they all have values
                $phones.filter(':last').after( '<input type="text" name="phone" class="phone" type="numbers" />' );
             }
         });
    });