views:

141

answers:

2

I've tried searching around but there isn't something that is a fairly concrete example of this, and my 'jQuery-Foo' Is rather poor.

Here's what I'm trying to accomplish:

User is presented with a form in which they enter user data (first/last/address, etc).

When it comes time to add a phone number, they need to be able to add as many as they would like. Through jQuery, how would i add another textbox to the form at a specific div (say div id="phoneNumbers"), and have those textbox values be added to the resulting formcollection object on save?

Would this sort of scenario even work? Can anyone suggest a better option for accomplishing this?

Thanks in Advance

+2  A: 

Hasn't anyone told you? You can do anything in jQuery ;)

Here's what the code might look like.

$("#phoneNumbers").append(
      "<input type=\"textbox\" id=\"newTxtBox\" name=\"newTxtBox\" />");

...

// Post the form with all values
$.post("/target/action", $("#myform").serialize());

Note that your div called "phoneNumbers" would have to be in the form "myform" for the new textbox value to be serialized and posted.

This seems like a reasonable approach as long as you can be sure that all your users will have javascript enabled. However, it's always suggested to have a "graceful degradation" backup approach for when javascript cannot be used. The way I usually implement this is by adding a button to the form, like "add another phone number", that if clicked, would post back to the server and generate a new form with an additional text box. In my jQuery document.ready() function, I'd just hide the button.

womp
So to call that .Append method, would i do that via an 'OnClick' handler on the button or link to append the values?Thanks though, You ROCK!
LandonGN
Yep, exactly. Also, if you're not too familiar with posting a form with jquery, I'd suggest reading up on it a bit. You can use other overloads of the $.post() function to specify callback functions that will handle the response from posting the form. So you could display a dialog, or add a message saying "submit successful", or whatever you'd like.
womp
A: 

So something like this will technically be correct?

var current = 1;

   function addNumber() {
       console.log('running addNumber')
       //current keeps track of how many numbers we have.
       current++;
        var thePhoneBox = ('<p> <label for="number ' + current + '>number' + current + ':</label> <%= Html.TextBox("number' + current + '") %>\n <%= Html.ValidationMessage("number ' + current + '", "*") %>\n </p>'
       console.log(thePhoneBox)
       $('#phoneNumbers').append(thePhoneBox)
   }

   $(document).ready(function() {
       $('#addNumber').click(addNumber)
   });

Thanks much for your help.

LandonGN