推广jQuery动态添加/删除多个表单的表单输入 [英] Generalizing jQuery dynamic add/remove form input for multiple forms

查看:174
本文介绍了推广jQuery动态添加/删除多个表单的表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个功能正常的代码,用于在我的页面上动态添加和删除表单输入。我有多个表单需要包含在页面中,因此我做了一个事件操作,他们可以按下按钮,并隐藏除相关表单之外的所有表单。这工作得很好,但它创建了与我的jQuery / JavaScript代码冲突,因为代码使用类名来动态添加或删除输入字段。这两种形式都必须在同一个类名下,才能按原样使用jQuery函数,但这会产生冲突,并且该函数将停止工作。我可以只写两个版本的函数(每个类都有一个版本),但我试图找到一种方法来概括这个,这样我就不必有太多的函数。我正在考虑这样做:

  $('。ccinput')。addClass('dinput')。removeClass( 'ccinput'); 

其中我会相应地更改每个表单的类名,以便它们成为唯一与jQuery函数。这种方法似乎非常容易出错,尤其是对于2个以上的表格(我计划总共有4个表格)。你们知道另一种我可以做到的方式吗?这里是我的HTML代码供参考:编辑:我已经对代码做了重大修改,所以这里是新版本。我删除了表单输入中的所有ID值,并更改了jQuery函数,以便它不使用ID值作为选择器。这消除了一些冲突。我正在尝试使用attr('class','newclass'),以便jQuery函数适用于这两种代码。它似乎对第一种形式完美地起作用,但它拒绝为第二种形式发挥作用。我不知道为什么。

 < html> 

< head>
< title>< / title>
< script src =http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js>< / script>
< script src =jquery.maskedinput.jstype =text / javascript>< / script>

< script type =text / javascript>
$(document).ready(function(){
$(#table1)。hide();
$(#table2)。hide();
$(#cc_button)。click(function(){
$(#table1)。show();
$(#table2)。hide();
$(#cctable tr)。attr('class','dinput');
$(#dbtable tr)。attr('class','dbinput');
} );
$(#db_button)。click(function(){
$(#table2)。show();
$(#table1)。hide );
$(#dbtable tr)。attr('class','dinput');
$(#cctable tr)。attr('class','ccinput');
$)($#$ b $('#btnAdd')。click(function(){
var num = $('。dinput')。length; //多少个duplicateatable输入字段我们目前有
var newNum = new Number(num + 1); //添加新输入字段的数字ID

//通过clone()创建新元素,和男人使用newNum值使用它的ID
var newElem = $('。dinput:last')。clone();

//在最后一个duplicateatable输入字段后插入新元素
$('。dinput:last')。after(newElem);
$(。dinput:last td:first)。replaceWith(< td>+ newNum +< / td>);

//启用删除按钮
$('#btnDel')。attr('disabled','');

$(。date)。mask(99/99/9999);
$ b $ //商业规则:只能添加20个名字
if(newNum == 20)
$('#btnAdd')。attr('disabled','disabled );
});

'('#btnDel')。click(function(){
var num = $('。dinput')。length; //我们目前有多少个重复输入字段有
$('。dinput:last')。remove(); //删除最后一个元素

//启用添加按钮
$('#btnAdd ').attr('disabled','');

//如果只剩下一个元素,则禁用remove按钮
if(num-1 == 1)
$('#btnDel')。attr('disabled','disabled');
});

$(。date)。mask(99/99/9999);
});
< / script>
< / head>
< body>
< div id =tablebuttons>
< button type =buttonid =cc_button> CC< / button> < button type =buttonid =db_button> DB< / button>
< / div>
< div id =table1>

< form id =ccardsmethod =postaction =<?php echo htmlentities($ PHP_SELF);?>>
< table border =1cellspacing =0>
< tr>
< th>< / th>
th#(最后四位数字)< / th>
< th>金额< / th>
< th>批准< / th>
th收到的日期< / th>
< / tr>
< tbody id =cctable>
< tr class =ccinput>
< td> 1< / td>
< td> < input type =textname =cc_num []maxlength =4/> < / TD>
< td> < input type =intname =cc_amnt []/> < / TD>
< td> < input type =textname =cc_app []maxlength =10/> < / TD>
< td> < input class =datetype =textname =cc_date []/> < / TD>
< / tr>
< / tbody>
< / table>
< div>
< input type =buttonid =btnAddvalue =Add CC/>
< input type =buttonid =btnDelvalue =Remove CC/>
< / div>
< input type =submitvalue =Submitname =submit/>
< / form>
< / div>
< div id =table2>

< form id =dbmethod =postaction =<?php echo htmlentities($ PHP_SELF);?>>
< table border =1cellspacing =0>
< tr>
< th>< / th>
< th> DB#< / th>
< th>金额< / th>
< th>日期< / th>
< / tr>
< tbody id =dbtable>
< tr class =dbinput>
< td> 1< / td>
< td> < input type =textname =db_num []/> < / TD>
< td> < input type =intname =db_amnt []/> < / TD>
< td> < input class =datetype =textname =db_date []/> < / TD>
< / tr>
< / tbody>
< / table>
< div>
< input type =buttonid =btnAddvalue =Add DB/>
< input type =buttonid =btnDelvalue =Remove DB/>
< / div>
< input type =submitvalue =Submitname =submit/>
< / form>
< / div>
< / body>

< / html>


解决方案

好的,我解决了它。

  $(#$) (); $ b $(#table2)。hide(); 
$(#table1)。 ('class','dinput');
$(#dbtable tr)。attr('class','dbinput');
});
$(#db_button)。click(function(){
$(#table2)。show();
$(#table1)。hide();
$(#dbtable tr)。attr('class','dinput');
$(#cctable tr)。attr('class','ccinput');
});

这基本上根据按下哪个按钮来更改每个表的class属性。从理论上讲,这应该适用于4种形式,尽管我还没有尝试过。这是更新后的代码(自从第一个代码以来,我已经改变了很多),这些代码用于那些想查看我做过的事情:

 < HTML> 

< head>
< title>< / title>
< script src =http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js>< / script>
< script src =jquery.maskedinput.jstype =text / javascript>< / script>

< script type =text / javascript>
$(document).ready(function(){
$(#table1)。hide();
$(#table2)。hide();
$(#cc_button)。click(function(){
$(#table1)。show();
$(#table2)。hide();
$(#cctable tr)。attr('class','dinput');
$(#dbtable tr)。attr('class','dbinput');
} );
$(#db_button)。click(function(){
$(#table2)。show();
$(#table1)。hide );
$(#dbtable tr)。attr('class','dinput');
$(#cctable tr)。attr('class','ccinput');
});
$('。btnAdd')。click(function(){
var num = $('。dinput')。length; //多少个duplicatable输入字段我们目前有
var newNum = new Number(num + 1); //添加新输入字段的数字ID

//通过clone()创建新元素,和男人使用newNum值使用它的ID
var newElem = $('。dinput:last')。clone();

//在最后一个duplicateatable输入字段后插入新元素
$('。dinput:last')。after(newElem);
$(。dinput:last td:first)。replaceWith(< td>+ newNum +< / td>);

//启用删除按钮
$('。btnDel')。attr('disabled','');

$(。date)。mask(99/99/9999);
$ b $ //商业规则:只能添加20个名字
if(newNum == 20)
$('。btnAdd')。attr('disabled','disabled );
});
$ b $('。btnDel')。click(function(){
var num = $('。dinput')。length; //我们目前有多少个重复输入字段有
$('。dinput:last')。remove(); //删除最后一个元素

//启用添加按钮
$('。btnAdd ').attr('disabled','');

//如果只剩下一个元素,则禁用remove按钮
if(num-1 == 1)
$('。btnDel')。attr('disabled','disabled');
});

$(。date)。mask(99/99/9999);
});
< / script>
< / head>
< body>
< div id =tablebuttons>
< button type =buttonid =cc_button> CC< / button> < button type =buttonid =db_button> DB< / button>
< / div>
< div id =table1>

< form id =ccardsmethod =postaction =<?php echo htmlentities($ PHP_SELF);?>>
< table border =1cellspacing =0>
< tr>
< th>< / th>
th#(最后四位数字)< / th>
< th>金额< / th>
< th>批准< / th>
th收到的日期< / th>
< / tr>
< tbody id =cctable>
< tr class =ccinput>
< td> 1< / td>
< td> < input type =textname =cc_num []maxlength =4/> < / TD>
< td> < input type =intname =cc_amnt []/> < / TD>
< td> < input type =textname =cc_app []maxlength =10/> < / TD>
< td> < input class =datetype =textname =cc_date []/> < / TD>
< / tr>
< / tbody>
< / table>
< div>
< input type =buttonclass =btnAddvalue =Add/>
< input type =buttonclass =btnDelvalue =Remove/>
< / div>
< input type =submitvalue =Submitname =submit/>
< / form>
< / div>
< div id =table2>

< form id =dbmethod =postaction =<?php echo htmlentities($ PHP_SELF);?>>
< table border =1cellspacing =0>
< tr>
< th>< / th>
< th> DB#< / th>
< th>金额< / th>
< th>日期< / th>
< / tr>
< tbody id =dbtable>
< tr class =dbinput>
< td> 1< / td>
< td> < input type =textname =db_num []/> < / TD>
< td> < input type =intname =db_amnt []/> < / TD>
< td> < input class =datetype =textname =db_date []/> < / TD>
< / tr>
< / tbody>
< / table>
< div>
< input type =buttonclass =btnAddvalue =Add/>
< input type =buttonclass =btnDelvalue =Remove/>
< / div>
< input type =submitvalue =Submitname =submit/>
< / form>
< / div>
< / body>

< / html>


Currently I have a functioning code for dynamically adding and removing form inputs on my page. I have multiple forms that I need to include on the page, so I made an event action where they could press a button and it would hide all the forms except the relevant one. This worked fine, but it created a conflict with my jQuery/javascript code because the code uses a class name to dynamically add or remove input fields. Both forms would have to be under the same class name for me to use the jQuery function as is, but that creates conflict and the function stops working. I could just write two versions of the function (one for each class), but I'm trying to find a way to generalize this, so that I don't have to have so many functions. I was thinking about doing something like this:

$('.ccinput').addClass('dinput').removeClass('ccinput');

where I would change each form's class name accordingly, so that they would be the only ones communicating with the jQuery function. This method seems to be very error prone, especially with more than 2 forms (I plan on having 4 forms total). Do you guys know of another way that I can accomplish this? Here is my html code for reference:

EDIT: I've made significant changes to the code, so here is the new version. I removed all the ID values from the form inputs and changed the jQuery function so that it does not use ID values as selectors. This removed some conflicts. And I'm now trying to use attr('class','newclass') so that the jQuery function works for both codes. It seems to work perfectly for the first form, but it refuses to function for the second. I have no idea why.

<html>

<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $("#table1").hide();
        $("#table2").hide();
        $("#cc_button").click(function(){
            $("#table1").show();
            $("#table2").hide();
            $("#cctable tr").attr('class', 'dinput');
            $("#dbtable tr").attr('class', 'dbinput');
        });
        $("#db_button").click(function(){
            $("#table2").show();
            $("#table1").hide();
            $("#dbtable tr").attr('class', 'dinput');
            $("#cctable tr").attr('class', 'ccinput');
        });
        $('#btnAdd').click(function() {
            var num     = $('.dinput').length; // how many "duplicatable" input fields we currently have
            var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

            // create the new element via clone(), and manipulate it's ID using newNum value
            var newElem = $('.dinput:last').clone();

            // insert the new element after the last "duplicatable" input field
            $('.dinput:last').after(newElem);
            $(".dinput:last td:first").replaceWith( "<td>" + newNum + "</td>" );

            // enable the "remove" button
            $('#btnDel').attr('disabled','');

            $(".date").mask("99/99/9999");

            // business rule: you can only add 20 names
            if (newNum == 20)
                $('#btnAdd').attr('disabled','disabled');
        });

        $('#btnDel').click(function() {
            var num = $('.dinput').length; // how many "duplicatable" input fields we currently have
            $('.dinput:last').remove();     // remove the last element

            // enable the "add" button
            $('#btnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('#btnDel').attr('disabled','disabled');
        });

        $(".date").mask("99/99/9999");
    });
</script>
</head>
<body>
<div id="tablebuttons">
<button type="button" id="cc_button">CC</button> <button type="button" id="db_button">DB</button>
</div>
<div id="table1">

<form id="ccards" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table border="1" cellspacing="0">
<tr>
<th></th>
<th># (last four digits)</th>
<th>Amount</th>
<th>Approval</th>
<th>Date Received</th>
</tr>
<tbody id ="cctable" >
<tr class="ccinput">
    <td> 1 </td>
    <td> <input type="text" name="cc_num[]" maxlength="4" /> </td> 
    <td> <input type="int" name="cc_amnt[]" /> </td>
    <td> <input type="text" name="cc_app[]" maxlength="10" /> </td> 
    <td> <input class="date" type="text" name="cc_date[]" /> </td>
</tr>
</tbody>
</table>
<div>
    <input type="button" id="btnAdd" value="Add CC" />
    <input type="button" id="btnDel" value="Remove CC" />
</div>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<div id="table2">

<form id="db" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table border="1" cellspacing="0">
<tr>
<th></th>
<th>DB #</th>
<th>Amount</th>
<th>Date</th>
</tr>
<tbody id="dbtable">
<tr class="dbinput">
    <td> 1 </td>
    <td> <input type="text" name="db_num[]" /> </td> 
    <td> <input type="int" name="db_amnt[]" /> </td> 
    <td> <input class="date" type="text" name="db_date[]" /> </td>
</tr>
</tbody>
</table>
<div>
    <input type="button" id="btnAdd" value="Add DB" />
    <input type="button" id="btnDel" value="Remove DB" />
</div>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</body>

</html>

解决方案

Okay, I solved it. There were multiple issues with my selectors that I had to fix, but after that the following solution works perfectly:

$("#cc_button").click(function(){
  $("#table1").show();
  $("#table2").hide();
  $("#cctable tr").attr('class', 'dinput');
  $("#dbtable tr").attr('class', 'dbinput');
});
$("#db_button").click(function(){
  $("#table2").show();
  $("#table1").hide();
  $("#dbtable tr").attr('class', 'dinput');
  $("#cctable tr").attr('class', 'ccinput');
});

This basically changes the class attribute of each table according to which button is pressed. Theoretically, this should work for 4 forms, though I have not tried it yet. This is the updated code (I've changed a lot since the first code) for those that want to see what I did:

<html>

<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $("#table1").hide();
        $("#table2").hide();
        $("#cc_button").click(function(){
            $("#table1").show();
            $("#table2").hide();
            $("#cctable tr").attr('class', 'dinput');
            $("#dbtable tr").attr('class', 'dbinput');
        });
        $("#db_button").click(function(){
            $("#table2").show();
            $("#table1").hide();
            $("#dbtable tr").attr('class', 'dinput');
            $("#cctable tr").attr('class', 'ccinput');
        });
        $('.btnAdd').click(function() {
            var num     = $('.dinput').length; // how many "duplicatable" input fields we currently have
            var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

            // create the new element via clone(), and manipulate it's ID using newNum value
            var newElem = $('.dinput:last').clone();

            // insert the new element after the last "duplicatable" input field
            $('.dinput:last').after(newElem);
            $(".dinput:last td:first").replaceWith( "<td>" + newNum + "</td>" );

            // enable the "remove" button
            $('.btnDel').attr('disabled','');

            $(".date").mask("99/99/9999");

            // business rule: you can only add 20 names
            if (newNum == 20)
                $('.btnAdd').attr('disabled','disabled');
        });

        $('.btnDel').click(function() {
            var num = $('.dinput').length; // how many "duplicatable" input fields we currently have
            $('.dinput:last').remove();     // remove the last element

            // enable the "add" button
            $('.btnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('.btnDel').attr('disabled','disabled');
        });

        $(".date").mask("99/99/9999");
    });
</script>
</head>
<body>
<div id="tablebuttons">
<button type="button" id="cc_button">CC</button> <button type="button" id="db_button">DB</button>
</div>
<div id="table1">

<form id="ccards" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table border="1" cellspacing="0">
<tr>
<th></th>
<th># (last four digits)</th>
<th>Amount</th>
<th>Approval</th>
<th>Date Received</th>
</tr>
<tbody id ="cctable" >
<tr class="ccinput">
    <td> 1 </td>
    <td> <input type="text" name="cc_num[]" maxlength="4" /> </td> 
    <td> <input type="int" name="cc_amnt[]" /> </td>
    <td> <input type="text" name="cc_app[]" maxlength="10" /> </td> 
    <td> <input class="date" type="text" name="cc_date[]" /> </td>
</tr>
</tbody>
</table>
<div>
    <input type="button" class="btnAdd" value="Add" />
    <input type="button" class="btnDel" value="Remove" />
</div>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<div id="table2">

<form id="db" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table border="1" cellspacing="0">
<tr>
<th></th>
<th>DB #</th>
<th>Amount</th>
<th>Date</th>
</tr>
<tbody id="dbtable">
<tr class="dbinput">
    <td> 1 </td>
    <td> <input type="text" name="db_num[]" /> </td> 
    <td> <input type="int" name="db_amnt[]" /> </td> 
    <td> <input class="date" type="text" name="db_date[]" /> </td>
</tr>
</tbody>
</table>
<div>
    <input type="button" class="btnAdd" value="Add" />
    <input type="button" class="btnDel" value="Remove" />
</div>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</body>

</html>

这篇关于推广jQuery动态添加/删除多个表单的表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆