【问题标题】:Showing hidden div with jquery .each() function使用 jquery .each() 函数显示隐藏的 div
【发布时间】:2013-12-17 21:34:46
【问题描述】:

我正在尝试使用 jQuery 验证表单。我正在选择所有具有class="required" 的表单字段并使用.each() 函数来检查该字段是否为空。如果它是空的,我将显示相对于该字段定位的隐藏 div。

由于以下代码失败,显然有问题:

$('#application').submit(function(){
var requiredFields = $('.required').val();
requiredFields.each(function(){
    if (requiredFields == ''){
        position = requiredFields.position();
        width = requiredFields.outerWidth();
        $("#error-wrapper-mail").css({
            visibility: "visible",
            top: (pos.top - 8) + "px",
            left: (pos.left + width + 25) + "px"
        }).hide().fadeIn("slow").delay(2700).fadeOut("slow");
        requiredFields.addCLass("not-valid").focus().delay(3500).queue(function(){
            $(this).removeClass("not-valid");
        });
        return false;
    }
}); });

如果我按 ID 选择输入字段,其余代码工作正常。

标记:

<form role="form" id="application" action="add-customer.php" method="post" enctype="multipart/form-data">
    <label for="Input-firstname">First name<span class="redstar"> * </span></label>
    <input type="text" class="form-control required" id="Input-firstname" name="firstname" placeholder="Your first name">
    <br />
    <label for="Input-lastname">Last name<span class="redstar"> * </span></label>
    <input type="text" class="form-control required" id="Input-lastname" name="lastname" placeholder="Your last name">
    <br />
    <label for="InputPass">Password<span class="redstar"> * </span></label>
    <input type="password" class="form-control  required" id="InputPass" name="pass" placeholder="Choose your password">
    <span class="help-block">Please create a password more than 6 symbols long, including uppercase letters, lowercase letters and digits.</span>
    ...
</form>

我是 jQuery 新手,如果有人能指出正确的方向,我将不胜感激

编辑:这是小提琴 - http://jsfiddle.net/7yLmq/

【问题讨论】:

  • 只是一个旁注,它是addClass 而不是addCLass

标签: javascript jquery html css


【解决方案1】:

尝试在每个$('.required') 之间循环:

$('.required').each(function(){
   var requiredFields = $(this).val();
   // Your Code
});

【讨论】:

  • 看起来合乎逻辑,但仍然无法正常工作......感谢您的建议,也许问题出在其他地方......
  • 嗨@Belgor,如果您需要更多帮助,请尝试使用您提供的代码在jsfiddle.net 中重现您的问题,我无法重现,仅建议我看到的代码:)
  • 是的,你是对的......这是小提琴jsfiddle.net/7yLmq这看起来很简单,但我无法让它工作......
  • 您希望为每个字段显示消息吗?
  • 是的,我只想有一个 div 用作错误消息,并相对于空字段显示它
【解决方案2】:

您的代码也可以通过使用其他一些 jQuery 方法来清理。

$('#application').submit(function(){
  $('.required').each(function(){
    if($(this).val() == ''){
      $(this).closest('.help-block').fadeIn();
      return false;
    }
  });
});

这假设每个required 输入字段都有一个help-block。您可以很容易地调整这一点,将 help-block 移动到当前的 required 字段,但是除非您希望动态加载这些消息,否则我看不到重点。

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多