确保选择了多个选择元素选项

时间:2017-07-19 23:17:39

标签: javascript jquery

我有一个由具有X行数的循环创建的表。每行都有一个选择。我想循环遍历每个选择,如果没有选择值,则完全停止该功能并且不提交表单。现在的问题是,如果一行有一个选定的值,而有两行没有,它将提交那一行,但我需要它不提交,除非所有行都有一个选定的值。

这是一个jsfiddle,有一个问题的例子

https://jsfiddle.net/ypx91hk0/2/

代码



function save() {

  let order = [];

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

    if (value === 'empty') {
      console.log("empty");
      $(".alertEmptySelect").show();
      return;
    }

    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);
      }
    });
  });
}
&#13;
 

<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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

您可以在每个循环之前添加一个检查。

var hasEmptySelect = $('select[name="statusSelect[]"]')
   .map((idx, elem) => elem.value)
   .filter(value => value === "empty")
   .length > 0;

所以你以:

结束
function save() {

    let order = [];

    var hasEmptySelect = $('select[name="statusSelect[]"]')
       .map((idx, elem) => elem.value)
       .filter(value => value === "empty")
       .length > 0;

    if (hasEmptySelect) {
        return;
    }

    // The rest of your code
}

答案 1 :(得分:0)

您可以为ajax调用创建单独的函数,并仅在order.length === $('select').length表示已选择所有选择时调用该函数。

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");
      alert('empty');
      $(".alertEmptySelect").show();
      return;
    }

    alert('Saving...');

    // else continue if all selects have a value 
    order.push({
      id: id,
      status: value
    });
    if(order.length === $('select').length)
       saveValues(JSON.stringify(order));
  });

  function saveValues(data){
  $.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)

首先解释:我建议在循环外保留一个变量,比如var flag = 0。然后,只有当循环满足您的条件时,才会在循环的每次迭代中将此标志值递增1,即;为该行的select元素选择了一个选项。

循环完成所有迭代后,检查flag变量的值是否等于循环的迭代次数。也就是说,如果总共有5个选择元素,则当循环结束时,如果每个选择元素具有用户选择的选项/值,则flag的值将为5。然后只提交表单/调用ajax函数。以下是有效的代码。我正在使用jquery。 :

<!DOCTYPE html>
    <html>
    <body>
    <select name="statusSelect[]" id="statusSelect" onchange="changeColor(this, 123)" class="form-control" required>
      <option value="empty" disabled selected hidden>Please Choose...</option>
      <option id="123" value="a">A</option>
      <option id="456" value="r">R</option>
    </select>
    <select name="statusSelect[]" id="statusSelect"  class="form-control" required>
      <option value="empty" disabled selected hidden>Please Choose...</option>
      <option id="123" value="a">A</option>
      <option id="456" value="r">R</option>
    </select>
    <select name="statusSelect[]" id="statusSelect" class="form-control" required>
      <option value="empty" disabled selected hidden>Please Choose...</option>
      <option id="123" value="a">A</option>
      <option id="456" value="r">R</option>
    </select>
    <select name="statusSelect[]" id="statusSelect"  class="form-control" required>
      <option value="empty" disabled selected hidden>Please Choose...</option>
      <option id="123" value="a">A</option>
      <option id="456" value="r">R</option>
    </select>
    <button>
    Save
    </button>

    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
    <script>
    $(document).ready(function(){
    $('button').click(function(){
      let flag = 0, rows = 0;
      let order = [];

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

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

        else //since a value was selected, increase flat by 1 and add order to array that will be used in ajax function as data
        {
          flag =  flag + 1;
          order.push({
            id: id,
            status: value
          });
        }
      });    //end of loop


      //now check if flag variable = total number of iterations/rows
        if(flag == rows)
        {   //call ajax and etc. etc.
         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);
            }
          });
        } 

        // else if flag != row, show alert to user
        else alert('select all options');

      });
     }); 
    </script>
    </body>
    </html>