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

时间:2012-07-19 00:47:31

标签: javascript jquery toggle

我正在使用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>

2 个答案:

答案 0 :(得分:1)

$(".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');
});

答案 1 :(得分:0)

$(".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/