2016-09-29 53 views
0

我試圖使用「+」和「 - 」按鈕來允許用戶在多選測驗創建應用程序中爲每個問題添加或減少可能選擇的數量。如何使用按鈕允許用戶添加/減少輸入元素並保持元素值序列?

的每個問題選擇的最大數是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); 
    }); 

回答

0

取而代之的是找到無線電元素的最後一個val,我在.choices ul的子節點上調用.length,將其存儲在每個按鈕單擊的變量上,並在if語句中使用,並且按照它應該的方式工作。

0

爲什麼叫一個令人費解(和低性能)像這樣的掃描選擇器?也許你有一個理由?

如果是我,我只是將ID添加到按鈕,並直接調用它們。 $('#radioid')。value();

沿着這些線的東西。這有幫助嗎?尋找父母/孩子和掃描下來,直到你找到一些東西,恕我直言,不惜一切代價避免。有時候它很有用,但它真的會在一年內重構頁面時創建一個主要的噩夢,並且某人不知道您的dom掃描代碼會更改HTML,然後您的代碼開始針對它們的HTML運行,並且jquery的樂趣真正開始。

確實有幫助嗎?

使用ID可以節省您的生活在jQuery中。