猿问

选择“单选按钮”中的一个选项时如何禁用其他选项?

我试图在选择一个选项后立即禁用其他选项,但使用 java 脚本我无法做到这一点。请帮我。到目前为止我已经尝试过


 <?php 

    $answer = $exm->getAnswer($number);


    if ($answer) {

        while ($result = $answer->fetch_assoc()) {

?>

            <tr>

                <td>

                 <input id="question_radio" type="radio" name="ans" value="<?php echo $result['id']; ?>"/><?php echo $result['ans']; ?>




<script id="question_radio" type="text/javascript">$(":radio").click(function(){

   var radioName = $(this).attr("ans"); //Get radio name

  $(":radio[name='"+radioName+"']:not(:checked)").attr("disabled", true); //Disable all unchecked radios with the same name

});             


            </script>



                </td>

            </tr>

<?php } } ?>

            <tr>

              <td>

                <input type="submit" name="submit" value="Next Question"/>

                <input type="hidden" name="number" value="<?php echo $number; ?>" />


                </td>

            </tr>


撒科打诨
浏览 126回答 2
2回答

子衿沉夜

您可以获得name单选按钮的属性,clicked根据这个属性,我们将遍历所有具有该名称的单选按钮和disable未选中的单选按钮。这是演示代码:$("input[type=radio]").click(function() {&nbsp; //getting name attribute if radio which is clicked&nbsp; var name = $(this).attr("name");&nbsp; console.log(name)&nbsp; //loop only through those radio where name is same&nbsp; $('input[name="' + name + '"]').each(function() {&nbsp; &nbsp; //if not selected&nbsp; &nbsp; if ($(this).is(":not(:checked)")) {&nbsp; &nbsp; &nbsp; // add disable&nbsp; &nbsp; &nbsp; $(this).attr('disabled', 'disabled');&nbsp; &nbsp; }&nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input id="question_radio" type="radio" name="ans" value="<?php echo $result['id']; ?>" /> A<input id="question_radio" type="radio" name="ans" value="<?php echo $result['id']; ?>" />B<input id="question_radio" type="radio" name="ans" value="<?php echo $result['id']; ?>" />C<br><input id="question_radio" type="radio" name="ans1" value="<?php echo $result['id']; ?>" />A<input id="question_radio" type="radio" name="ans1" value="<?php echo $result['id']; ?>" /> B<input id="question_radio" type="radio" name="ans1" value="<?php echo $result['id']; ?>" />C

陪伴而非守候

这是纯 Javascript 的实现document.querySelectorAll("input[type=radio]").forEach(function (el) {&nbsp; el.addEventListener('click', function () {&nbsp; &nbsp; //getting name attribute if radio which is clicked&nbsp; &nbsp; var name = el.getAttribute('name');&nbsp; &nbsp; //loop only through those radio where name is same.&nbsp; &nbsp; document.querySelectorAll('input[name="' + name + '"]').forEach(function (el) {&nbsp; &nbsp; &nbsp; if (el.matches(":not(:checked)")) {&nbsp; &nbsp; &nbsp; &nbsp; el.setAttribute('disabled', 'disabled');&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; });});
随时随地看视频慕课网APP
我要回答