简体   繁体   English

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

[英]Ensure Multiple Select Element Has Non Empty Option Selected

I have a dropdown where the default selected option has a value of empty . 我有一个下拉列表,其中默认选择的选项的值为empty After clicking the submit button the save() function is called where if any of the selects have 'empty' chosen its suppose to display an alert and break. 单击提交按钮后, save()调用save()函数,在该函数中,如果任何选择都选择了“空”以显示警报并中断。 It displays the alert but if I choose an option for each select it never submits the post. 它显示警报,但是如果我为每个选择都选择一个选项,它将永远不会提交该帖子。 What am I doing wrong? 我究竟做错了什么?

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);
                }
            });
        }
    });
}

I have a table which is created by a loop. 我有一个由循环创建的表。 Each row has its own select which is why I have it declared as an array 每行都有自己的选择,这就是为什么我将其声明为数组

<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>

First of all, You need to change from PUT to POST have a look Here 首先,您需要从PUT更改为POST看看这里

Second, you needn't go to the server with every valid select but what you should do is collect your data and then if all valid go do ajax request so your function should look like this: 其次,您不必带着每个有效的选择都进入服务器,但是您应该做的是收集数据,然后如果所有有效的go都执行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);
    }
  });
}

It seems like you are simply forgetting to close your empty value condition: 似乎您只是在忘记关闭空值条件:

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);
      }
    });
  });
}

Agree with @twmulloy, curly braces issue. 同意@twmulloy,花括号问题。

Validate no empty selection on all dropdowns: 验证所有下拉列表中没有选择:

  // 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;
  }

Reuse list of all dropdowns to iterate through each dropdowns: allDropdowns.each 重用所有下拉列表以遍历每个下拉列表: allDropdowns.each

JsFiddle and overall code for save function: 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);
      }
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM