2012-07-19 65 views
0

我正在使用JQuery toggle()函數來允許用戶在表單中動態地將新值添加到選擇框。jQuery,在切換中重置表單值()

如果用戶點擊「添加」,將顯示一個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> 
+0

除非你在你的頁面有一個''元素,第二行是不正確。 – 2012-07-19 00:50:22

+0

您能否詳細說明您的問題,以便我能理解您想要做什麼以及哪些不起作用? – 2012-07-19 00:51:27

+0

對不起大家,看起來像我原來的帖子錯過了我添加的HTML,它應該更清楚。 – 2012-07-19 00:51:50

回答

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'); 
}); 
+0

感謝Sabith,除了檢查文本的價值之外,還有哪些方法可以做到這一點? – 2012-07-19 01:02:51

+0

@JasonWells您是否擔心文本將來發生變化或者代碼縮減? – sabithpocker 2012-07-19 01:16:53

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/