views:

125

answers:

2

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.
A: 

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.

Lazarus
Even though you can use same name for multiple elements, you need to specify different ids for them.
SolutionYogi
Yes, thanks, but as Yogi says, still got the same problem with the ids duplicating. Not quite sure how asp.net MVC binding works, but is it not reliant on the id matching the object field. Also though putting the html in the javascript is a viable solution, it doesn't degrade, therefore not entirely appropriate.
Richbits
That's not correct, it will work as given. I use this approach for a variable length form which has 2 text inputs per line and then a final line with a variable length number of checkboxes. The text inputs are effectively all named "numeric" and "comment", the checkboxes are all named = "check" (although they do have unique 'value's). The controller action accepts three arrays string[] numeric, string[] comment, string[] check.
Lazarus
A: 

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&amp;&amp; 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.

Richbits