2013-02-13 86 views
-2

新的輸入我有我的窗體上的下拉稱爲roomfac1,我想roomfac2roomfac3 ...(重複下拉菜單)被添加當用戶點擊添加按鈕。我如何使用jQuery完成此操作?除此之外,我還希望用戶動態刪除新創建的輸入。添加使用jQuery

我在這裏上傳我的代碼:http://jsfiddle.net/ecRXP/2/

<select name="roomFac1" id="roomFac1"> 
    <option selected="selected">Any</option> 
</select> 
<input type="button" value="Add" class="pmbtn" id="addFac"/> 
<input type="button" value="Remove" class="pmbtn" id="removeFac"/> 
+2

您的代碼不包含任何JavaScript的;這可能是爲什麼它不起作用= p – 2013-02-14 00:14:06

回答

3
$(document).ready(function(){ 
    $('#addFac').click(function(){ 
     var $objs = $('select[name*=roomFac]'); 
     var n = $objs.size() + 1; 
     var $obj = $objs.first().clone(); 
     $obj.attr('name', 'roomFac'+n).attr('id', 'roomFac'+n); 
     $obj.appendTo($('body')); 
    }); 
    $('#removeFac').click(function(){ 
     var $objs = $('select[name*=roomFac]'); 
     if($objs.size() > 1){ 
      $objs.last().remove(); 
     } 
    }); 
}); 

,這裏是小提琴:http://jsfiddle.net/kfm5b/2/

+0

你將如何去除最近添加的輸入? – methuselah 2013-02-14 00:22:50

+1

這裏你去,編輯 – pwolaq 2013-02-14 00:23:57

+0

它很好,但我不得不問的最後一個問題是我將如何防止第一個roomFac(即roomFac1)被刪除? – methuselah 2013-02-14 00:28:14

1

Example on jsFiddle

HTML:

<form> 
    <div class="add"> 
     <a href="#" id="add">Add</a> 
    </div> 
    <div class="row"> 
     <select name="roomFac1" id="roomFac1"> 
      <option selected="selected">Any</option> 
     </select> 
    </div> 
</form> 

JS:

var $form = $("form"), 
    $firstRow = $(".row:first"), 
    totalRows; 

$("form").on("click", ".delete", function (e) { 
    e.preventDefault(); 

    $(this).closest("div").remove(); 
}); 

$("#add").on("click", function (e) { 
    var $clonedRow = $firstRow.clone(), 
     totalRows = "1", 
     newNum; 

    e.preventDefault(); 

    totalRows = $(".row").length; 
    newNum = parseInt(totalRows, 10) + 1; 

    $clonedRow.find("select").attr("name", "roomFac" + newNum); 
    $clonedRow.find("select").attr("id", "roomFac" + newNum); 
    $clonedRow.append('<a href="#" class="delete">Delete</a>'); 
    $form.append($clonedRow); 
}); 
1

我想你可以使用.clone,像這樣:

var roomFacCount = 1; 

$('#addFac').on('click', function() { 
    var $lastRoomFac = $('#roomFac' + roomFacCount); 
    roomFacCount++; 
    $lastRoomFac.after($lastRoomFac.clone(true, true).attr('id', 'roomFac' + roomFacCount)); 
}); 

$('#removeFac').on('click', function() { 
    if (roomFacCount > 1) { 
     var $lastRoomFac = $('#roomFac' + roomFacCount); 
     roomFacCount--; 
     $lastRoomFac.remove(); 
    } 
}); 

Demo on jsfiddle