2016-05-17 93 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...'); 
    } 

});