使用jquery获取select元素的值

时间:2016-10-28 16:02:40

标签: php jquery ajax

我有以下HTML

<div class="question-set">
      <div class="row question">
        <div class="col-md-2">
          <select class="form-control" name="type[]">
            <option value="Teacher feedback">Teacher feedback</option>
            <option value="Genral Question">Genral Question</option>
            <option value="Informative Question">Informative Question</option>
          </select>
        </div>
        <div class="col-md-8">
          <input type="text" class="form-control" name="questions[]" placeholder="Enter the question here" />
        </div>
      </div>
      <div class="row question">
        <div class="col-md-2">
          <select class="form-control" name="type[]">
            <option value="Teacher feedback">Teacher feedback</option>
            <option value="Genral Question">Genral Question</option>
            <option value="Informative Question">Informative Question</option>
          </select>
        </div>
        <div class="col-md-8">
          <input type="text" class="form-control" name="questions[]" placeholder="Enter the question here" />
        </div>
      </div>
    </div>

简而言之,有一个名称类型为[]的选择标记和一个文本输入字段名称问题[]。我需要将值传递给php页面作为ajax调用以插入数据库。我有以下AJAX代码..

  $.ajax({
          method: "POST",
          url: "feedback_create_form_process.php",
          data: {"questions": $("input[name='questions[]']").val(), "type": $("select option:selected").val()},
          success: function(data){
            alert(data);
          }
        });

这是我的PHP代码

<?php
  include 'con.php';
  if (isset($_POST) && sizeof($_POST)) {
    $question = $_POST['questions'];
    $type = $_POST['type'];

    echo count($question);
    foreach( $question as $key => $n ) {
      $result = $con->query("insert into form question(null, ".$question[$key].", ".$n.")");
    }
  }
?>

计数返回1.它只发送第一个问题,而不是数组。我想要一个数组中的值,所以我可以在循环中插入。

2 个答案:

答案 0 :(得分:2)

在JQuery .Val()

中记录
  

描述:获取匹配元素集中第一个元素的当前值。

您可以使用

var values = $("input[name='questions[]']").map(function(){return $(this).val();}).get();

var values = [];
$("input[name='questions[]']").each(function() {
    values.push($(this).val());
});

答案 1 :(得分:0)

您可以使用jQuery的map()函数将值作为数组返回,如下所示:

var questions = $("input[name='questions[]']").map(function() {return $(this).val()}).get();
var types = $("select[name='type[]']").map(function() {return $(this).val()}).get();

$.ajax({
     method: "POST",
     url: "feedback_create_form_process.php",
     data: {"questions": questions, "type": types},
     success: function(data){
         alert(data);
     }
});

编辑: ABDU_GO提供了类似的解决方案。我发现我的脚本更具可读性,但是如果你发现这是你的解决方案,我建议接受他的答案。

相关问题