0

在许多字段集中,我使用下一步按钮尝试查找是否有“#required” id 输入,然后,如果它为空,则返回 false(留在此字段集中),否则继续操作...

if ($(this).attr('required').length == 0) {
    alert ('oui');
    if (!$(this).attr('required')) 
        return false;
}
else 
    alert ('non');

不过$(this).attr('required').lengthundefined因为没id找到。

需要帮助,谢谢大家。

我解释:在字段集(动态创建)中,如果存在 id #required 的输入,我必须检查它是否为空。如果是,单击按钮将返回 false。我是法国人,也是 jQuery 新手,所以对一切感到抱歉 =\

的HTML:

[...]
   <fieldset>
      <h2 class="fs-title">Accueil Particulier</h2>
      <h3 class="fs-subtitle">Nombre de personnes :</h3>
      <input type="number" class="required" name="par_venu_f" placeholder="Femme(s)"/>
      <input type="number" class="required" name="par_venu_h" placeholder="Homme(s)"/>
      <br/><br/><input type="button" name="previous" class="previous action-button" value="Pr&eacute;c&eacute;dent"/>
      <input type="button" name="next" class="next action-button" value="Suivant"/>
   </fieldset>
[...]

编辑 :

好的,现在我在这里:

  if ($(this).parent().children().hasClass('required')) {
    if ($(this).parent().children('.required').val().length == 0) {
      alert('find, empty')
      return false;
    };
    alert ('find, full');
  }
  else alert ('not find');

没关系,但是当它只检查第一个输入 [type=text] 时,我如何检查其他输入?

编辑 2:我尝试了 .each() 函数,但不明白它是如何工作的......

回答 :

非常感谢@TrueBlueAussie,即使我在几分钟前发现了这个:

  //check if class="required" exist
  if ($(this).parent().children().hasClass('required')) {
    //start of each class="required"
    $(this).parent().children('.required').each(function() {
      //if empty, do not continue
      if ($(this).val().length == 0) {fill_required = false;};
    //end each
    });
  // end if exist
  };

  // if there is one empty field, will be false so ...
  if (!fill_required) {
    // make it true before leave then ...
    fill_required = true;
    // leave.
    return false;
  //end if one empty
  };
4

1 回答 1

0

你不应该在一个页面上有重复的 id。使用classordata-...属性代替您的“必需”标志,因为它们通常不止一个。

您还需要检查标志的存在(不是它的长度),然后检查输入的值(例如 with val())。看起来您正在将“必需”测试与“输入字段值为空白”测试混为一谈。

如果您使用属性(如data-required=""),您的代码将类似于:

if ($(this).data('required') && $(this).val().length == 0) {
    alert ('oui');
    return false;
}
else 
    alert ('non');

如果你使用一个类,它看起来像:

if ($(this).hasClass('required') && $(this).val().length == 0) {
    alert ('oui');
    return false;
}
else 
    alert ('non');

在这种情况下,我个人建议使用 required 类,因为这也意味着您可以对必填字段的样式有所不同(输入周围的不同颜色边框等)。

您可能还想在长度检查之前修剪您的值,以便忽略空白(空格)

更新 - 基于对问题的更改:

如果要检查所有“必填”字段,则需要像这样循环:

   // Default is "OK to submit"
   var allow = true;

   // test each required field for a value
   $('.required').each(function(){
       $input = $(this);

       // If we don't have a value, abort with "NOT OK to submit"
       if ($input.val().length == 0){
            allow = false;
            return false;   // <<< this just aborts the each() call
       }
   }
   if (allow){
       alert ('non');
   }
   else {
       alert ('oui');
       return false;
   }

可以简化/缩短,但我希望它清楚它的作用。

于 2013-09-27T10:41:49.767 回答