我試圖使用「+」和「 - 」按鈕來允許用戶在多選測驗創建應用程序中爲每個問題添加或減少可能選擇的數量。如何使用按鈕允許用戶添加/減少輸入元素並保持元素值序列?
的每個問題選擇的最大數是4,最小值爲2
我來補防的是,添加的選擇之後,減按鈕無法讀取的最後一個單選按鈕的價值問題。
此外,單選按鈕的值在那裏,因爲它們在應用程序的其他部分中使用,而不僅僅是用於此功能。因此,重要的是單選按鈕的選擇是連續的,從0開始。
非常感謝您提供任何提示。
這裏是一個Codepen,但我使用的代碼也低於:http://codepen.io/anon/pen/zKdzZv?editors=1010
HTML:
<div id="q-container">
<div class="qelem">
<h4>Question 1.)</h4>
<input type="text" class="question" style="width:400px"
placeholder=" Who was the 2nd president of the United States?">
<br>
<br>
<ul style="list-style:none;" class="choices">
<li><input type="radio" name="rad" value="0"><input type="text" class="choice" placeholder=" John Hancock"></li>
<li><input type="radio" name="rad" value="1"><input type="text" class="choice" placeholder=" Adam Smith"></li>
<li><input type="radio" name="rad" value="2"><input type="text" class="choice" placeholder=" John Adams"></li>
</ul>
<br>
<div class="btn-group btn-group-xs choiceAmt" role="group">
<button type="button" class="btn" id="add"><small><span class="glyphicon glyphicon-plus"></span></small></button>
<button type="button" class="btn" id="sub"><small><span class="glyphicon glyphicon-minus"></span></small></button>
</div>
</div>
</div>
的JavaScript:
$("#add").click(function(){
var num;
var lastRadioVal = $(this).parents(".qelem").find("input:radio").last().val();
console.log("lastRadioVal = " +lastRadioVal);
num = lastRadioVal+1;
$(this).parents(".qelem").children(".choices").append(
'<li><input type="radio" name="rad" value="'+num+'">
<input type="text" class="choice"></li>'
);
if(lastRadioVal = 3){
$(this).prop('disabled',true);
}
if(lastRadioVal > 1){
$("#sub").prop('disabled',false);
}
console.log("lastRadioVal = " +lastRadioVal);
});
$("#sub").click(function(){
var lastRadioVal = $(this).parents(".qelem").find("input:radio").last().val();
console.log("lastRadioVal = " +lastRadioVal);
$(this).parents(".qelem").find("li").last().remove();
lastRadioVal--;
if(lastRadioVal = 1){
$(this).prop('disabled', true);
}
$("#add").prop('disabled', false);
console.log("lastRadioVal = " +lastRadioVal);
});