jQuery,在toggle()中重置表单值

jQuery, resetting form value in a toggle()

本文关键字:表单 toggle jQuery      更新时间:2023-11-27

我使用JQuery toggle()函数允许用户在表单中动态地向选择框添加新值。

如果用户单击"添加",则会显示一个DIV,其中包含一个输入框,并且"添加"文本将更改为"删除"。

如果用户单击"添加",然后在新的输入框中输入一些文本,然后单击"删除",我想清除输入框。

这里的一切都有效,但我不清楚在用户切换"删除"的情况下,如何重置新创建的输入框的表单值

这是我的代码

$(".newName").click(function(){
    var frm = $(this).closest("form"); 
    $(".newContainer", frm).toggle(); // toggles the newContainer to show or hide
    $(this).text($(this).text() == 'Add' ? 'Remove' : 'Add'); // changes our text 
    $("#nameList", frm).prop('disabled', $(this).text() != 'Add') // disables the original list if we are adding a new one
});
<div class="names">
    <form id="newForm">
        <select id="nameList"></select>
        <p><a href="#" class="newName">Add</a></p>
        <div class="newContainer">
            <input type="text" id="theNewName" />
        </div>
    </form>
</div>
$(".newName").click(function(){
    var frm = $(this).closest("form"); 
    $(".newContainer", frm).toggle(); // toggles the newContainer to show or hide
    if($(this).text() == 'Remove'){$("#nameList", frm).val('');}
    $(this).text($(this).text() == 'Add' ? 'Remove' : 'Add'); // changes our text 
    $("#nameList", frm).prop('disabled', $(this).text() != 'Add') // disables the original list if we are adding a new one
});

如果你担心文本("添加"/"删除")被更改+一些优化:

<a href="#" class="newName add" data-add-text="Add" data-remove-text="Remove">
Add
</a>

$('body').on('click',".newName",function(){
    var frm = $(this).closest("form"); 
    $(".newContainer", frm).toggle();
    $("#nameList", frm).val('').prop('disabled', $(this).hasClass('remove'));
    var newText = $(this).hasClass('remove')?
        $(this).data('addText'):$(this).data('removeText');
    $(this).text(newText).toggleClass('add remove');
});
$(".newName").click(function(){
    var frm = $(this).closest("form");
    $(".newContainer", frm).toggle(); // toggles the newContainer to show or hide
    $(this).text($(this).text() == 'Add' ? 'Remove' : 'Add'); // changes our text
    if($(this).text() == 'Remove' )
    {
    $("#theNewName",frm).val('');
    }
    $("#nameList", frm).prop('disabled', $(this).text() != 'Add') // disables the original list if we are adding a new one
});

请在此处查看演示:http://jsfiddle.net/