Tutorial :add templated div to page multiple times with different ids



Question:

I am using ASP.Net MVC along with Jquery to create a page which contains a contact details section which will allow the user to enter different contact details:

           <div id='ContactDetails'>                    <div class='ContactDetailsEntry'>                  <select id="venue_ContactLink_ContactDatas[0]_Type" name="venue.ContactLink.ContactDatas[0].Type"><option>Email</option>                      <option>Phone</option>                      <option>Fax</option>                  </select>                  <input id="venue_ContactLink_ContactDatas[0]_Data" name="venue.ContactLink.ContactDatas[0].Data" type="text" value="" />                  </div>                </div>              <p>                  <input type="submit" name="SubmitButton" value="AddContact" id='addContact'/>  </p>  

Pressing the button is supposed to add a templated version of the ContactDetailsEntry classed div to the page. However I also need to ensure that the index of each id is incremented.

I have managed to do this with the following function which is triggered on the click of the button:

function addContactDetails()      {          var len = $('#ContactDetails').length;            var content = "<div class='ContactDetailsEntry'>";              content += "<select id='venue_ContactLink_ContactDatas["+len+"]_Type' name='venue.ContactLink.ContactDatas["+len+"].Type'><option>Email</option>";               content += "<option>Phone</option>";               content += "<option>Fax</option>";               content += "</select>";               content += "<input id='venue_ContactLink_ContactDatas["+len+"]_Data' name='venue.ContactLink.ContactDatas["+len+"].Data' type='text' value='' />";               content += "</div>";          $('#ContactDetails').append(content);      }   

This works fine, however if I change the html, I need to change it in two places.

I have considered using clone() to do this but have three problems:

EDIT: I have found answers to questions as shown below:

  1. (is a general problem which I cannot find an answer to) how do I create a selector for the ids which include angled brackets, since jquery uses these for a attribute selector. EDIT: Answer use \ to escape the brackets i.e. $('#id\\[0\\]')
  2. how do I change the ids within the tree.

EDIT: I have created a function as follows:

function updateAttributes(clone, count) {           var f = clone.find('*').andSelf();          f.each(function(i){                          var s = $(this).attr("id");          if (s!=null&& s!="")          {          s = s.replace(/([^\[]+)\[0\]/, "$1["+count+"]");          $(this).attr("id", s);          }});  

This appears to work when called with the cloned set and the count of existing versions of that set. It is not ideal as I need to perform the same for name and for attributes. I shall continue to work on this and add an answer when I have one. I'd appreciate any further comments on how I might improve this to be generic for all tags and attributes which asp.net mvc might create.

  1. how do I clone from a template i.e. not from an active fieldset which has data already entered, or return fields to their default values on the cloned set.


Solution:1

You could just name the input field the same for all entries, make the select an input combo and give that a consistent name, so revising your code:

       <div id='ContactDetails'>                <div class='ContactDetailsEntry'>              <select id="venue_ContactLink_ContactDatas_Type" name="venue_ContactLink_ContactDatas_Type"><option>Email</option>                  <option>Phone</option>                  <option>Fax</option>              </select>              <input id="venue_ContactLink_ContactDatas_Data" name="venue_ContactLink_ContactDatas_Data" type="text" value="" />              </div>            </div>          <p>              <input type="submit" name="SubmitButton" value="AddContact" id='addContact'/>  </p>  

I'd probably use the Javascript to create the first entry on page ready and then there's only 1 place to revise the HTML.

When you submit, you get two arrays name "venue_ContactLink_ContactDatas_Type" and "venue_ContactLink_ContactDatas_Data" with matching indicies for the contact pairs, i.e.

venue_ContactLink_ContactDatas_Type[0], venue_ContactLink_ContactDatas_Data[0]  venue_ContactLink_ContactDatas_Type[1], venue_ContactLink_ContactDatas_Data[1]  ...  venue_ContactLink_ContactDatas_Type[*n*], venue_ContactLink_ContactDatas_Data[*n*]  

Hope that's clear.


Solution:2

So, I have a solution which works in my case, but would need some adjustment if other element types are included, or if other attributes are set by with an index included.

I'll answer my questions in turn:

  1. To select an element which includes square brackets in it's attributes escape the square brackets using double back slashes as follows: var clone = $("#contactFields\[0\]").clone();

  2. & 3. Changing the ids in the tree I have implemented with the following function, where clone is the variable clone (in 1) and count is the count of cloned statements.

    function updateAttributes(clone, count) { var attribute = ['id', 'for', 'name']; var f = clone.find('*').andSelf(); f.each(function(i){

                    var tag = $(this);            $.each(attribute, function(i, val){                    var s = tag.attr(val);                  if (s!=null&& s!="")                      {                      s = s.replace(/([^\[]+)\[0\]/, "$1["+count+"]");                      tag.attr(val, s);                      }          });   if ($(this)[0].nodeName == 'SELECT')   { $(this).val(0);}   else   {       $(this).val("");   }  });  

    }

This may not be the most efficient way or the best, but it does work in my cases I have used it in. The attributes array could be extended if required, and further elements would need to be included in the defaulting action at the end, e.g. for checkboxes.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »