如何检查是否使用Jquery检查了动态生成的单选按钮?

时间:2019-10-07 07:36:11

标签: jquery html button

我们有一个包含MCQ类型问题的问卷,该问卷是使用laravel中的刀片动态生成的。我想检查是否使用单选按钮回答了每个问题。如果用户留下其中一个问题,我不希望提交表单。

我编写了以下代码,但是此代码的问题是,当用户留下所有问题(最后一个问题除外)时,我的意思是当他仅回答提交表单时的最后一个问题时。请记住,即使有一个问题没有答案,我也不想提交表格。

<form action="/result" method="POST" id="form1">
  @csrf

  @php
    $count=0
  @endphp

 @foreach ($questions[$sections->id] as $question)
  <div class="ans" align="center">
    <div class="opt">

      <div class="row1">
        <label class="label">{{ $question->question }}</label>
      </div>

    <div class="ans">

     @php
      $answer=$answers[$question->id]
     @endphp

     @foreach ($answer as $answer)
      <label class="btn btn-default no-margin-rule" >
       <input type="radio" name="{{$count+1}}" value="{{$answer->id}}" id="ans{{$answer->answer}}" />
       <span class="option{{$answer->answer+1}}"></span>
      </label>
     @endforeach

    </div>
   </div>
  </div>

@endforeach
</form>
<div style="overflow: auto;">
  <div style="height:50px;">
    <div id="submitText" class="alert alert-danger" style="display:none">
      <strong>Can't Submit!</strong> Please select all options first, then click on submit.
    </div>
   </div>
    <button id="sub"   class="btn-self-submit float-right">Submit</button>&nbsp;&nbsp;&nbsp;
</div>
$("#sub").click(function(){
   var check = true;
   $("input:radio").each(function(){
     var name= $(this).attr('name');

     if($("input:radio[name="+name+"]:checked").length){
       check = true;
     }

     else{
      check=false;
     }

   });

   if(check){
     $("#form1").submit();
   }

   else{
     swal("Oops!", "Please select at least one answer in each question.", "error")
    }
});

7 个答案:

答案 0 :(得分:0)

默认情况下,表单内的button元素会自动视为type="submit",因此单击后立即触发表单提交。为了防止这种情况并自己处理提交,请将按钮设置为type="button"

$("#sub").click(function(ev) {
  var check = false;
  $("input:radio").each(function() {
    var name = $(this).attr('name');

    if ($("input:radio[name=" + name + "]:checked").length) {
      check = true;
    } else {
      check = false;
    }

  });

  if (check) {
    $("#form1").submit();
  } else {
    console.log("Please select at least one answer in each question.");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
  Q1 <input type="radio" name="q1" value="A"> <input type="radio" name="q1" value="B"> <input type="radio" name="q1" value="C"><br> Q2 <input type="radio" name="q2" value="A"> <input type="radio" name="q2" value="B"> <input type="radio" name="q2" value="C"><br>  Q3 <input type="radio" name="q3" value="A"> <input type="radio" name="q3" value="B"> <input type="radio" name="q3" value="C"><br>
  <button id="sub" type="button">submit</button>
</form>

答案 1 :(得分:0)

可以简化为这一假设,假设每个问题有3个答案

$("#sub").click(function(e) {
  var rads = $("input:radio");
  var checked = $("input:radio:checked");
  if (rads.length / 3 !== checked.length) {
    e.preventDefault();
    alert("Please select at least one answer in each question.");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
  Q1 <input type="radio" name="q1" value="A"> <input type="radio" name="q1" value="B"> <input type="radio" name="q1" value="C"><br> Q2 <input type="radio" name="q2" value="A"> <input type="radio" name="q2" value="B"> <input type="radio" name="q2" value="C"><br>  Q3 <input type="radio" name="q3" value="A"> <input type="radio" name="q3" value="B"> <input type="radio" name="q3" value="C"><br>
  <button id="sub" type="submit">submit</button>
</form>

答案 2 :(得分:0)

您可以简化一下,我假设每个问题都有一个单选按钮,因此您可以将:checked的长度与radio的按钮长度进行比较。

$("#submit").click(function(e) {
   let check = false;
   if($('input:radio:checked').length == $('input:radio').length) {
     check = true;
   }

   if(check) {
     //submit form
   }
   console.log(check)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<lable>
   Q 1 <input type="radio" name="q1">
</lable>
<lable>
    Q 2 <input type="radio" name="q2">
</lable>
<lable>
    Q 3 <input type="radio" name="q3">
</lable>
  
<button id="submit">submit</button>

答案 3 :(得分:0)

这可能有效-我尚未测试过,也未使用jQuery,但希望它可能会有所帮助

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>jQuery: Radio buttons</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
    </head>
    <body>
        <form id='form1' method='post'>
            <?php
                /* 
                    to roughly emulate the contents of the original form simply for testing 
                    generate some html input elements with mickey mouse values
                */
                for( $i=1; $i <= 10; $i++ ){

                    echo '<div>Question: '.$i.'<br />';


                    for( $j=1; $j <= 5; $j++ ){ 
                        printf('
                            <label>%2$d
                                <input type="radio" name="radio_%1$d" value="%1$d" />
                            </label>', 
                            $i, 
                            $j
                        );
                    }
                    echo '</div>';
                }

            ?>
            <input type='button' id='sub' value='Submit' />
        </form>

        <script>

            /* to avoid errors, replicate `swal` function */
            const swal=function(h,m,t){
                console.info(h,m,t);
                alert( m )
            }



            $( "#sub" ).click(function(e){

                let checked=[];
                let unchecked=[];

                $( "input:radio" ).each(function(){
                    let name= $(this).attr('name');


                    if( $( "input:radio[ name="+name+" ]:checked " ).length == 1 )checked.push( name );
                    else unchecked.push( name );

                });

                if( unchecked.length === 0 ){
                    $("#form1").submit();
                } else{
                    swal("Oops!", "Please select at least one answer in each question.", "error")
                }
            });
        </script>
    </body>
</html>

答案 4 :(得分:0)

这是我的方法。提交尝试完成后,我将执行检查,因为可以通过单击或按Enter键来提交表单。其余内容在评论中进行了描述。

$('#form1').submit(function() {
    var submit = true; // Submit form if all radio buttons are checked.
    var errors = {}; // Store potential errors if some of the inputs is not checked.
    var radio_groups = {}; // Store the inputs grouped by name.

    $("#form1 input[type=radio]").each(function() { // Group the inputs.
        radio_groups[this.name] = true;
    });

    for(group_name in radio_groups) { // Check if the inputs are checked
        if (!$(":radio[name='" + group_name + "']:checked").length) {
           errors[group_name] = group_name + " is not checked!"; // Set error messages.
           submit = false; // Prevent form submission if there's an empty radio input.
        }
    }

    $.each(errors, function(key, value){
        alert(value); // Alert all errors.
    });
    return submit;
});

如果您的表单ID为“ form1”,则此代码应为您开箱即用。 哦,还有一件事-使用整数作为输入名称不是一个好主意。

答案 5 :(得分:0)

请点击使用

$("#sub").click(function(){});
replace with 
$("p").on("click", function(){));

答案 6 :(得分:0)

<script>
   const swal=function(h,m,t)
   {
     console.info(h,m,t);
     alert( m )
   }

   $( "#sub" ).click(function(e)
   {
     let checked=[];
     let unchecked=[];
     $( "input:radio" ).each(function()
     {
        let name= $(this).attr('name');
        if( $( "input:radio[ name="+name+" ]:checked").length == 1 )checked.push(name);

        else unchecked.push( name );

     });

     if( unchecked.length === 0 )
     {
      $("#form1").submit();
     } 
     else
     {
       swal("Oops!", "Please select at least one answer in each question.", "error")
     }
     });
</script>