繁体   English   中英

防止空字符串成为数组的一部分

[英]prevent empty strings from being part of an array

如何使我的函数仅在输入字段中填写内容时才发送数据? 我有一个标准的4个输入字段,每当我在2个输入字段中插入数据时,它都会向我的数组中发送2个单词(有效),但它也会发送2个空字符串。 但是,我希望数组仅以值存在,而不是空字符串。 一个简单的例子:您作为用户决定填写4个输入字段中的2个(因为它们是可选的)。 我现在想防止其他2个输入字段也向我的JSON发送一个空字符串。 因此,只有用户填写的内容才能成为数组的一部分。

这是我的函数为我的数组创建输入字段的外观:

function getWordPartInput(id, cValue) {
  console.log(cValue);
  cValue = cValue || '';
  var div = $('<div/>');
  for (let i = 0; i < 4; i++) {
    var wpInput = $('<input/>', {
      'class': 'form-group form-control syllable syl ' + TT ++,
      'type': 'text',
      'value': (cValue[i] !== undefined) ? cValue[i] : '',
      'placeholder': 'Syllables',
      'name': 'Syllablescounter['+ i +']'
    });
    div.append(wpInput);
  }
  return div;
}

这是AJAX调用:

function saveExerciseAjaxCall() {
  console.log(setMainObjectArray());

  $.ajax({
    url: 'saveJson.php',
    type: 'POST',
    data: {
      id: getUrlParameter('id'),
      getExerciseTitle: $('#getExerciseTitle').val(),
      language: $('#languageSelector').val(),
      application: 'lettergrepen',
      'main_object': {
        title: $('#getExerciseTitle').val(),
        language: $('#languageSelector').val(),
        exercises: setMainObjectArray()
      },
      dataType: 'json'
    }
  }).done(function(response) {
  }).fail(function(jqXHR, textStatus, errorThrown){
    console.log(jqXHR);
    console.log(errorThrown);
    console.log(textStatus);
  });
}

setMainObjectArray()的外观如下:

我说的是数组syllables

 function setMainObjectArray() {
var exercises = [];
var eBlocks = $('.eBlock');

eBlocks.each(function(i, eBlock) {
    var exObject = {
      word: $(eBlock).find('input.ExerciseGetWordInput').val(),
      syllables: []
    };
    $(eBlock).find('input.syllable').each(function(j, syll) {

      exObject.syllables.push($(syll).val());            
    });

    exercises.push(exObject);
  });

return exercises;
}

您可以这样做以避免音节被空值填充。

if($(syll).val() !== "") {
    exObject.syllables.push($(syll).val());
}

如果值为空,则可以输入IF条件和SKIP

function saveExerciseAjaxCall() {

  // This code will skip AJAX call if value is empty
  if($('#getExerciseTitle').val() == '') {
     return false;
  }

  console.log(setMainObjectArray());

  $.ajax({
    url: 'saveJson.php',
    type: 'POST',
    data: {
      id: getUrlParameter('id'),
      getExerciseTitle: $('#getExerciseTitle').val(),
      language: $('#languageSelector').val(),
      application: 'lettergrepen',
      'main_object': {
        title: $('#getExerciseTitle').val(),
        language: $('#languageSelector').val(),
        exercises: setMainObjectArray()
      },
      dataType: 'json'
    }
  }).done(function(response) {
  }).fail(function(jqXHR, textStatus, errorThrown){
    console.log(jqXHR);
    console.log(errorThrown);
    console.log(textStatus);
  });
}

暂无
暂无

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

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