arame3333
arame3333

Reputation: 10193

JQuery: I have a unique id for my form. How do I use that to select the element ids within it?

I have a form and I generate a unique Id for it. The idea is that if more than 1 form is generated, the duplicate ids on each form will not interfere with each other because I can reference the unique form Id for the first. However what I want to know is the syntax for doing this. So on the following View, I have some jquery script that reference a date field and a couple of checkboxes. As currently written, where I create more than 1 form, the Id for NullableOtherLeaveDate, MorningOnlyFlag, AfternoonOnlyFlag will be duplicated. I need to prefix them with the unique formId.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.EmployeeOtherLeaf>" %>
<% var unique = DateTime.Now.Ticks.ToString(); %>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $('#NullableOtherLeaveDate').datepicker({ dateFormat: 'dd-MM-yy' });
        $('#MorningOnlyFlag').click(function () {
            $('#AfternoonOnlyFlag').attr('checked', false);
        })
        $('#AfternoonOnlyFlag').click(function () {
            $('#MorningOnlyFlag').attr('checked', false);
        })
    });

    var options = {
        target: '#frmAddAbsenceOneDay<%= unique %>',
        success: RefreshList
    };

    $(document).ready(function () {
        $('#frmAddAbsenceOneDay<%= unique %>').ajaxForm(options);
    });

</script>

<div id="AddAbsenceOnDay<%= unique %>">

    <% using (Html.BeginForm("AddAbsenceOneDay", "Employee", FormMethod.Post,
           new { id = "frmAddAbsenceOneDay" + unique }))
       { %>
        <%: Html.ValidationSummary(true) %>
        <fieldset>
            <legend>Add an absence for a day or half day</legend>
            <table>
                <tr>
                    <td><%: Html.LabelFor(model => model.OtherLeaveId)%></td>
                    <td>
                <%: Html.DropDownListFor(model => model.OtherLeaveId, Model.SelectLeaveTypeList, "<--Select-->")%>
                <%: Html.ValidationMessageFor(model => model.OtherLeaveId)%>                    
                    </td>
                </tr>
                <tr>
                    <td>
                <%: Html.LabelFor(model => model.NullableOtherLeaveDate)%>                    
                    </td>
                    <td>
                <%: Html.EditorFor(model => model.NullableOtherLeaveDate)%>
                <%: Html.ValidationMessageFor(model => model.NullableOtherLeaveDate)%>
                <%if (ViewData["ErrorDateMessage"] != null && ViewData["ErrorDateMessage"].ToString().Length > 0)
                  { %>   
                                   <p class="error">
                   At <% Response.Write(DateTime.Now.ToString("T")); %>. <%: ViewData["ErrorDateMessage"]%>.
                </p>
                <%} %>                 
                    </td>
                </tr>
                <tr>
                    <td>
                <%: Html.LabelFor(model => model.MorningOnlyFlag)%>
                    </td>
                    <td>
                <%: Html.CheckBoxFor(model => model.MorningOnlyFlag)%>
                <%: Html.ValidationMessageFor(model => model.MorningOnlyFlag)%>                        
                    </td>
                </tr>
                <tr>
                    <td>
                <%: Html.LabelFor(model => model.AfternoonOnlyFlag)%>
                    </td>
                    <td>
                <%: Html.CheckBoxFor(model => model.AfternoonOnlyFlag)%>
                <%: Html.ValidationMessageFor(model => model.AfternoonOnlyFlag)%>                     
                    </td>
                </tr>
            </table>

            <p>
                <span style="padding-right:10px;"><input type="submit" value="Create" /></span><input type="button" value="Close" onclick="closeTab()" />
            </p>
        </fieldset>

    <% } %>
    </div>

Upvotes: 1

Views: 245

Answers (2)

Mutation Person
Mutation Person

Reputation: 30498

I would echo what everyone else is saying. IDs need to be unique.

For completeness, you can pull IDs in the manner you suggest:

<div id="one">
   <div id="three">
        hello1
   </div>
</div>
<div id="two">
   <div id="three">
        hello2
   </div>
</div>

...

alert($("#one #three").html());
alert($("#two #three").html());

http://jsfiddle.net/fn7XS/

But, I just wouldn't. Use a class as suggested elsewhere.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630409

This isn't a valid solution, IDs on elements need to be unique in the document, not just in any container you choose, several things depend on this. Instead use a class on the elements, with unique <form> IDs.

Then use class selectors, like this:

$('.NullableOtherLeaveDate')

And when looking inside a <form> for a specific one:

$('#frmAddAbsenceOneDayXXXXX .NullableOtherLeaveDate')

Why use classes? Because with invalid duplicate IDs things like this won't work:

 $('#NullableOtherLeaveDate').datepicker({ dateFormat: 'dd-MM-yy' });

The browser does document.getElementById("NullableOtherLeaveDate") which returns one element (as it should, it's unique, right?) so your .datepicker() would only run on the first id="NullableOtherLeaveDate" in most major browsers...the same is true for all your other ID operations.

Upvotes: 0

Related Questions