确保多个选择元素已选中非空选项

时间:2017-07-19 20:50:46

标签: javascript jquery

我有一个下拉列表,默认选中的选项的值为empty。单击提交按钮后,将调用save()函数,如果选择任何选项,则选择“空”,以显示警报并中断。它显示警报,但如果我为每个选择选择一个选项,它永远不会提交帖子。我做错了什么?

function save() {

    let order = [];

    $('select[name="statusSelect[]"]').each(function(){
        let id = this[this.selectedIndex].id;
        let value = this.value;

        // if any of the selects values === 'empty' break 
        if (value === 'empty') {
            console.log("empty");
            $(".alertEmptySelect").show();
            return;

            // else continue if all selects have a value 
            order.push({id: id, status: value});
            let data = JSON.stringify(order);

            $.ajax({
                method: 'put',
                url: '',
                data:  data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function(response){
                    $(".alertSubmitted").show("slow");
                },
                error: function (data) {
                    console.log(data);
                    let errorString = '';
                    $.each(data.responseJSON, function (key, value) {
                        errorString += '<li>' + value + '</li>';
                    });
                    $('.alertError').show().html(errorString);
                }
            });
        }
    });
}

我有一个由循环创建的表。每一行都有自己的选择,这就是为什么我将它声明为数组

<select name="statusSelect[]" id="statusSelect" onchange="changeColor(this, {{$product->id}})" class="form-control" required>
    <option value="empty" disabled selected hidden>Please Choose...</option>
    <option id={{$product->id}} value="a">A</option>
    <option id={{$product->id}} value="r">R</option>
</select>

3 个答案:

答案 0 :(得分:1)

首先,您需要从PUT更改为POST,看看Here

其次,你不需要每次有效选择都去服务器,但你应该做的是收集你的数据然后如果所有有效的去做ajax请求,那么你的函数应该是这样的:

    function save() {

  let order = [];
  //as you have many selects you need this flag to cancel ajax 
    request if any select is empyt
  let isEmpty = false;
  $('select[name="statusSelect[]"]').each(function() {
    let id = this[this.selectedIndex].id;
    let value = this.value;
    debugger;
    // if any of the selects values === 'empty' break the each
    //and set the flag to beak the ajax request
    if (value === 'empty') {
      console.log("empty");
      $(".alertEmptySelect").show();
      isEmpty = true;
      return;
    }
    // order array must be in the each loop to carry all the data
    order.push({
      id: id,
      status: value
    });

  });
  if (isEmpty) {
    console.log("save canceled");
    return;
  }
  let data = JSON.stringify(order);
  console.log(data);
  //should be outside the each to go only one time to the sever (make sure to put the Url)
  $.ajax({
    method: 'post',
    url: 'your Url',
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    success: function(response) {
      console.log('success.');
      $(".alertSubmitted").show("slow");
    },
    error: function(data) {
      console.log('error');
      console.log(data);
      let errorString = '';
      $.each(data.responseJSON, function(key, value) {
        errorString += '<li>' + value + '</li>';
      });
      $('.alertError').show().html(errorString);
    }
  });
}

答案 1 :(得分:0)

您似乎只是忘记关闭空值条件:

function save() {
  let order = [];

  $('select[name="statusSelect[]"]').each(function() {
    let id = this[this.selectedIndex].id;
    let value = this.value;

    // if any of the selects values === 'empty' break 
    if (value === 'empty') {
      console.log("empty");
      $(".alertEmptySelect").show();
      return;
    }

    // else continue if all selects have a value 
    order.push({id: id, status: value});
    let data = JSON.stringify(order);

    $.ajax({
      method: 'put',
      url: '',
      data:  data,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      async: false,
      success: function(response){
        $(".alertSubmitted").show("slow");
      },
      error: function (data) {
        console.log(data);
        let errorString = '';
        $.each(data.responseJSON, function (key, value) {
            errorString += '<li>' + value + '</li>';
        });
        $('.alertError').show().html(errorString);
      }
    });
  });
}

答案 2 :(得分:0)

同意@twmulloy,花括号问题。

在所有下拉列表中验证没有选项:

  // all dropdowns
  var allDropdowns = $('select[name="statusSelect[]"]');

  // empty selected options
  var emptySelectedOptions = allDropdowns.find('[value=empty]:selected');

  // flag if valid
  var isValid = (emptySelectedOptions.length === 0);

    if (!isValid){
    // exit
    alert('Please select option from all!');
    return;
  }

重复使用所有下拉列表来迭代每个下拉列表: allDropdowns.each

JsFiddle以及保存功能的整体代码:

function save() {

  let order = [];

    // all dropdowns
  var allDropdowns = $('select[name="statusSelect[]"]'),

    // empty selected options
    emptySelectedOptions = allDropdowns.find('[value=empty]:selected'),

    // flag if valid
    isValid = (emptySelectedOptions.length === 0);

 if (!isValid){
    // exit
    alert('Please select option from all!');
    return;
  }

  allDropdowns.each(function() {
    let id = this[this.selectedIndex].id;
    let value = this.value;

    alert('Saving...');

    // else continue if all selects have a value 
    order.push({
      id: id,
      status: value
    });
    let data = JSON.stringify(order);

    $.ajax({
      method: 'put',
      url: '',
      data: data,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      async: false,
      success: function(response) {
        $(".alertSubmitted").show("slow");
      },
      error: function(data) {
        console.log(data);
        let errorString = '';
        $.each(data.responseJSON, function(key, value) {
          errorString += '<li>' + value + '</li>';
        });
        $('.alertError').show().html(errorString);
      }
    });
  });
}