简体   繁体   English

asp.net jquery用文本框添加行(克隆行)并动态下拉

[英]asp.net jquery add row (clone row) with text box and drop down dynamically

When the user click's the add box attribute the row(ie the row with 2 dropdown and textbox needs to be added) row with above needs to be dynamically created using jquery(so that there is no post back). 当用户单击添加框属性时,行(即需要添加2下拉列和文本框的行)上面的行需要使用jquery动态创建(这样就没有回发帖)。 User will be allowed to add as many attirbutes as he wants and when they click the check box that row needs to be deleted. 用户可以根据需要添加任意数量的数据,并在单击复选框时需要删除该行。 How this can be achieved by jquery. 如何通过jquery实现这一点。

 <asp:Panel ID="pnl_BoxAttr" runat="server">
          <table>
             <tr>
                 <th>
                      Name
                  </th>
                  <th>
                      Comparision
                  </th>
                  <th>
                      Value
                  </th>
                  <th>
                      Delete
                  </th>
              </tr>
               <tr>
                   <td>
                       <asp:DropDownList ID="ddl_BoxName" runat="server">
                               <asp:ListItem Value="attr1" Selected="True"></asp:ListItem>
                               <asp:ListItem Value="attr2"></asp:ListItem>
                               <asp:ListItem Value="attr3"></asp:ListItem>
                       </asp:DropDownList>
                  </td>
                  <td>
                      <asp:DropDownList ID="ddl_BoxComparision" runat="server">
                             <asp:ListItem Value="=" Selected="true"></asp:ListItem>
                             <asp:ListItem Value=">"></asp:ListItem>
                             <asp:ListItem Value="<"></asp:ListItem>
                             <asp:ListItem Value="Like"></asp:ListItem>
                             <asp:ListItem Value="!="></asp:ListItem>
                             </asp:DropDownList>
                   </td>
                  <td>
                               <asp:TextBox ID="btn_boxval" runat="server" ></asp:TextBox>

                   </td>
                   <td>
                         <asp:CheckBox ID="chk_DeleteBoxRow" runat="server" />
                   </td>
             </tr>
             <tr>
                 <td colspan="3"> 
                     <asp:Button ID="btn_AddAttr" Text="Add Box Attribute" runat="server"/>
                 </td>
             </tr>
        </table>
        </asp:Panel>

To start with, here is a working demo, which you can reference throughout my answer: http://jsfiddle.net/EuyB8/ . 首先,这是一个工作演示,您可以在我的答案中引用: http//jsfiddle.net/EuyB8/

Obviously the demo is in plain HTML rather than ASP.NET, but I will try to address the differences. 显然,演示是纯HTML而不是ASP.NET,但我会尝试解决这些差异。

To start, since you will want to create some of the controls that you'll be cloning using .NET controls, my typical approach is to create a hidden template, which can then be used to create new copies. 首先,由于您将要创建一些使用.NET控件克隆的控件,我的典型方法是创建一个隐藏模板,然后可以使用该模板创建新副本。 As such, I would have a row like the following: 因此,我会有如下行:

<tr id="TemplateRow">
    <td>
        <asp:DropDownList ID="ddl_BoxName" runat="server">
            <asp:ListItem Value="attr1" Selected="True"></asp:ListItem>
            <asp:ListItem Value="attr2"></asp:ListItem>
            <asp:ListItem Value="attr3"></asp:ListItem>
        </asp:DropDownList>
    </td>
    <td>
        <asp:DropDownList ID="ddl_BoxComparision" runat="server">
            <asp:ListItem Value="=" Selected="true"></asp:ListItem>
            <asp:ListItem Value=">"></asp:ListItem>
            <asp:ListItem Value="<"></asp:ListItem>
            <asp:ListItem Value="Like"></asp:ListItem>
            <asp:ListItem Value="!="></asp:ListItem>
        </asp:DropDownList>
    </td>
    <td>
        <asp:TextBox ID="btn_boxval" runat="server" ></asp:TextBox>

    </td>
    <td>
        <asp:CheckBox ID="chk_DeleteBoxRow" runat="server" />
    </td>
</tr>

I then add a CSS rule like so: 然后我添加一个CSS规则,如下所示:

#TemplateRow { display:none; }

Now we have a row that we can use as a template for adding new rows, and the actual markup for the template can still be generated by .NET. 现在我们有一行可以用作添加新行的模板,并且.NET仍然可以生成模板的实际标记。 It is important to note that when using this approach with a table, the template row needs to be inside the table to which you'll be appending the rows, in order to ensure that the cells are the appropriate width. 需要注意的是,在对表使用此方法时,模板行需要位于要附加行的表的内部,以确保单元格的宽度适当。

The last bit of markup we'll need to do is to give the table an ID, so that we can manipulate the rows in our script. 我们需要做的最后一点标记是给表一个ID,以便我们可以操作脚本中的行。 I chose "BoxTable". 我选择了“BoxTable”。

Now, let's construct our script. 现在,让我们构建我们的脚本。 Because you are using .NET, it's important to remember that for any tag with the runat="server" attribute, the ID attribute that is generated is not the same as the one you assign in the control's ID field. 因为您使用的是.NET,所以请记住,对于具有runat="server"属性的任何标记,生成的ID属性与您在控件的ID字段中指定的ID属性不同。 An easy workaround for that is to do something like the following: 一个简单的解决方法是执行以下操作:

var myClientID = '<%= myServerID.ClientID() %>';

The server then outputs the client ID into a string for easy use in your script. 然后,服务器将客户端ID输出到字符串中,以便在脚本中使用。

With that in mind, here's our script: 考虑到这一点,这是我们的脚本:

var btn_AddAttr = '<%= btn_AddAttr.ClientID() %>';

$(function() {
    //attach the a function to the click event of the "Add Box Attribute button that will add a new row
    $('#' + btn_AddAttr).click(function() {
        //clone the template row, and all events attached to the row and everything in it
        var $newRow = $('#TemplateRow').clone(true);

        //strip the IDs from everything to avoid DOM issues
        $newRow.find('*').andSelf().removeAttr('id');

        //add the cloned row to the table immediately before the last row
        $('#BoxTable tr:last').before($newRow);

        //to prevent the default behavior of submitting the form
        return false;
    });

    //attach a remove row function to all current and future instances of the "remove row" check box
    $('#DeleteBoxRow').click(function() {
        //find the closest parent row and remove it
        $(this).closest('tr').remove();
    });

    //finally, add an initial row by simulating the "Add Box Attribute" click
    $('#' + btn_AddAttr).click();
});

I think the comments are pretty thorough, but a brief explanation of a few points is warranted: 我认为这些评论非常详尽,但有必要对以下几点进行简要说明:

First, when we clone the template row, we are passing a boolean to the clone function. 首先,当我们克隆模板行时,我们将布尔值传递给克隆函数。 This says that in addition to the DOM elements we are cloning, we should also clone the event handlers attached to those elements, and attach them to the new clones. 这说明除了我们克隆的DOM元素之外,我们还应克隆附加到这些元素的事件处理程序,并将它们附加到新克隆。 This is important in order for the "Delete Row" checkbox to work. 这对于“删除行”复选框起作用很重要。

Second, when we clone the template row, we are also cloning all the attributes of all the elements, including the IDs. 其次,当我们克隆模板行时,我们还克隆了所有元素的所有属性,包括ID。 We don't want this because it violates XHTML compliance and my cause problems. 我们不希望这样,因为它违反了XHTML合规性和我的原因问题。 Thus, we strip all the cloned elements of their IDs. 因此,我们剥离了其ID的所有克隆元素。

Lastly, because you are using a submit button, it's important to remember to return false in the button's click event, to avoid having it submit the form and cause a postback. 最后,因为您正在使用提交按钮,所以记住在按钮的单击事件中返回false非常重要,以避免它提交表单并导致回发。

Hopefully this answers your question. 希望这能回答你的问题。 One final thing to bear in mind is that since you are creating all these rows with jQuery, the server will not have objects ready to receive the values of the inputs. 最后要记住的是,由于您使用jQuery创建所有这些行,因此服务器不会准备好接收输入值的对象。 If you need the server to have access to that information, you'll have to figure out so method of sending it that information. 如果您需要服务器访问该信息,您必须找出向其发送该信息的方法。

As I understand it, you need the user to insert a new row (just like the one containing the select) by clicking a button? 据我了解,您需要用户通过单击按钮插入一个新行(就像包含选择的那一行)?

First you need to give the tr with the add button an id, let's say 'addTr'. 首先你需要给tr添加一个id按钮,让我们说'addTr'。

For inserting, you could do something like this: 对于插入,你可以这样做:

$('#btn_AddAttr').bind(
    'click',
    function() {
        $('#addTr').before( '<tr>' + 
                                /* entre tr content here */
                            '</tr>'
                          );
    }
);

Just be sure that all the dropdowns and textboxes have different ID's. 确保所有下拉菜单和文本框都有不同的ID。

For removing the row from the table, you should add a class that would help you identify all the delete checkboxes, let's say 'delChk': 要从表中删除行,您应该添加一个类,以帮助您识别所有删除复选框,让我们说'delChk':

$('.delChk').bind(
    'click',
    function() {
        $(this).closest('<tr>').remove();
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM