Laravel \ Blade - 获取动态添加的所选单选按钮的值

时间:2018-06-04 10:02:11

标签: javascript php jquery html laravel

我在Laravel开发了一份调查问卷。问题和他们的答案都打印出来。现在我需要检索每个问题的选定无线电/答案,以便将每对耦合插入索引数组中。问题是html标签无线电的名称是动态的而不是静态的,那么如何检索每个问题的答案呢?

在代码中,{{$ answer [0]}}是答案的ID,而{{$ answer [1]}}答案的文字

@foreach ($question->answers as $answer)

   <div class ="radio">
      <label>
         <input type="radio" name={{$question->id_question}} value= {{$answer[0]}}>
         {{$answer[1]}}
      </label>
   </div> 
@endif
@endforeach 

2 个答案:

答案 0 :(得分:1)

如果您正在寻找,请查看此内容:

 <div id="container">

    <div class ="radio01">
      <label for="question1">question1</label><input type="radio" name="question1"  id="question1" value="answer1">
      <label for="question1">question1</label><input type="radio" name="question1"  id="question1" value="answer2">
      <label for="question1">question1</label><input type="radio" name="question1"  id="question1" value="answer3">
      <label for="question1">question1</label><input type="radio" name="question1"  id="question1" value="answer4">
      <label for="question1">question1</label><input type="radio" name="question1"  id="question1" value="answer5">

   </div> 
    <div class ="radio02">
      <label for="question2">question2</label><input type="radio" name="question2"  id="question2" value="answer1">
      <label for="question2">question2</label><input type="radio" name="question2"  id="question2" value="answer2">
      <label for="question2">question2</label><input type="radio" name="question2" id="question2" value="answer3">
      <label for="question2">question2</label><input type="radio" name="question2"  id="question2" value="answer4">
      <label for="question2">question2</label><input type="radio" name="question2"  id="question2" value="answer5">

   </div> 

...

<script>
    var selectedAnswers = function () {

    var answers = [];

    $('input:radio').each(function () {

        var $this = $(this),

            name = $this.attr('name');
            value = $this.attr('value');

        if ($(this).prop('checked')) {
            answers.push({"name":name, "value":value});
        }

    });

    return answers;

};

$('#container').on('change', ':radio', function() { console.log(selectedAnswers()); }); 

</script>

此外,您的html不是“最佳”缺少双引号和正确的层次结构:

   <label>
     <input type="radio" name={{$question->id_question}} value= {{$answer[0]}}>
     {{$answer[1]}}
  </label>

应该(就像我上面的例子中一样):

     <input type="radio" name="{{$question->id_question}}"  id="{{$question->id_question}}" value=" {{$answer[0]}}">
     <label for="{{$question->id_question}}">{{$answer[1]}}</label>

答案 1 :(得分:0)

下面给出的函数来获取所有输入无线电的值。

function get_answers() {
    var answers = {};
    $.each($("input:radio"), function () {
        answers[$(this).attr("name")] = $(this).val();
    });
    return answers;
}