2016-05-17 181 views
1

我有一個在測驗遊戲中每個幻燈片上創建的按鈕。當您循環查看問題時,包含答案選項的單選按鈕將從對象附加到每張幻燈片中。我想要求單擊一個單選按鈕,然後才能訪問nextQuestion按鈕。您可以在下面的代碼的第5行(loadQuestion函數內部)找到.append()。什麼方法是達到預期結果的最佳方法?如果你需要更多的代碼,請告訴我。防止按鈕按下,直到選中單選按鈕

var loadQuestion = function(){ 
     $('.question-name').html(name + (qnum) +"/"+ total); 
     $('.question').html(questions[count].question); 
     for(var i=0; i<questions[count].options.length; i++) { 
      $('.inputs').append('<input type="radio" name="question" value="'+questions[count].options[i]+'">'+questions[count].options[i]+'<br>') 
     } 
    }; 

    /*--- First Question ---*/ 
    var name = "Question "; 
    var qnum = 1; 
    var count = 0; 
    var total = questions.length; 
    loadQuestion(); 

    /*--- When the Next Question Button is Hit ---*/ 
    nextQuestion.click(function() { 
     $('.inputs').html(""); 
     qnum++; 
     count++; 
     if (qnum <= 4) { 
      loadQuestion(); 
     } else if (qnum == 6) { 
      $('.question-name').html("Your Score:"); 
      $('.question').html("You got X out of 5 questions correct!"); 
      nextQuestion.html("Home Screen").click(function() { 
       location.reload(); 
      }); 
     } else if (qnum == 5){ 
      loadQuestion(); 
      $('.next-question').html("Get Score!"); 
     } 
    }); 
+0

一個辦法做到這一點是,在你點擊功能檢查是否選擇單選按鈕,如果虛假申報,否則你現在 – ashy

+1

在做什麼,如果一個單選按鈕被選中只是檢查繼續。 ($('input [name =「question」]:checked')。length> 0){// DOSTUFF –

回答

0
$(document).ready(function() { 
    $('#nextButton').attr('disabled', true);//disable the button by default on page load 
    $("input[type=checkbox]").on("click", function() { 
     if (this.length > 0) { 
      $('#nextButton').attr('disabled', false);//enable only when the checkbox is checked 
     } 
    }); 
}); 

我希望這有助於!

安全說明:任何人都可以使用瀏覽器中的開發人員工具從按鈕標記中刪除禁用的屬性。使用後端驗證複選框的值。

0

有去這個問題的方法不止一種:

「防止按下按鈕,直到無線電選擇了」

從UI/UX的角度您的要求提出了以下問題:「如果在收音機被選定之前用戶不應該點擊按鈕,爲什麼在收音機被選擇之前按鈕可以按下按鈕?「所以,我們從那裏開始。

//pseudo-code - use delegate binding '.on()' for dynamically generated elements 

$('.inputs').on('click', 'input[name="question"]', function({ 
    if ($(this).is(':checked')) { 
    $('#nextButton').attr('disabled', false); 
    } else { 
    $('#nextButton').attr('disabled', true); 
    } /*... snip ...*/ 
})); 

或者,你可以生成應答後nextButton選擇在您當前正在生成的單選按鈕一樣來 - 只記得使用委託事件綁定。這可能是「更好的方式」,因爲@zadd已經指出,disabled屬性可以規避。

沒有重新發明輪子,您也可以檢查當按下按鈕時是否選擇了收音機。

// pseudo-code again 
nextQuestion.click(function() { 

    if($('input[name="question"]:checked').length > 0){ 
     // checked!!! go do stuff!!! 
    } else { 
    // not checked! i should probably throw an alert or something... 
    alert('please answer the question before proceeding...'); 
    } 

});