.NET MVC Using Javascript to Add Textbox to View on Button Click

I tried searching, but there is no concrete example of this and my "jQuery-Foo" is pretty poor.

This is what I am trying to accomplish:

The 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 should be able to add as many as they like. Through jQuery, how would I add another textbox to the form on a specific div (say div id = "phoneNumbers"), and add those textbox values ​​to the resulting formcollection object on save?

Will this scenario work? Can anyone suggest a better option for this?

Thanks in Advance

+2


source to share


2 answers


Didn't nobody tell 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" must be in the form "myform" for the new textbox value to be serialized and published.

This seems like a sane approach as long as you can be sure that all of your users will have javascript enabled. However, it has always been suggested to use the "graceful degradation" approach when javascript cannot be used. As usual, I do this by adding a button to the form, such as "add another phone number", which when clicked will send it back to the server and generate a new form with an additional text field. In my jQuery document.ready () function, I'll just hide the button.

+2


source


So would something like this 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)
   });

      



Many thanks for your help.

0


source







All Articles