2013-08-24 62 views
1

我试图使用jquery检查带有动态创建的表单域的表单,以确保在提交之前填充了所有输入字段。我想隐藏提交链接,直到所有字段都填满。这是我迄今为止所拥有的。显示所有输入字段填充时的链接

$('form#form_id').change(function(e) { 
$(":input").each(function() { 
    if($(this).val() === ""){ 
     $("#showlink").hide(); 
     }else{ 
     $("#showlink").show(); 
     } 
    }); 
}); 
<div id="showlink"> 
     <a href="#" id="submitBtnId" onclick="addDuctClickHandler();" data-icon="check" data-role="button" data-inline="true" data-theme="b">Submit Final Test</a> 
</div> 

我在这里错过了什么吗?

+0

另一种方法是使用HTML5属性,在该HTML5属性上表单不能被子集化,直到所有必填字段被填充为止 –

+0

J eroen是正确的,谨慎的是,HTML5 API并非在所有的浏览器中都可用 –

回答

3

这应该做的伎俩:

// check for the change of any input in the form 
$('#form_id :input').change(function(e) { 

    // if any of the values are blank hide the link 
    if ($('#form_id :input').map(function(idx, elem) { 
      if ($(elem).val() === "") return $(elem); 
     }).size() > 0) 
     $("#showlink").hide(); 
    else 
     $("#showlink").show(); 
}); 

与您的代码的问题是,它是附加更改处理整个窗体,而不是输入;我甚至不确定这是什么影响。此外,您正在使用each函数遍历整个文档中的所有输入,而不仅仅是表单,并且链接将根据它们的值显示和隐藏每个输入,因此最终该链接将是可见或隐藏的仅在迭代中检查的最后一个值。

+0

我已经用你的例子设置了一个js小提琴......不要使用它很多,所以我认为我已经按照描述设置了它。它不是很有效。 http://jsfiddle.net/swJAq/ –

+0

@ChrisPilie我更新了我的答案,选择器只是有点关闭,它需要'$('#form_id:input')'而不是'$('form#form_id :输入')'。同样在你的jsfiddle中,你需要在showlink div中添加'style =“display:none”',这样它就可以隐藏起来。 – asymptoticFault

+0

谢谢!我更新了小提琴。它在那里工作,但仍然没有在我的代码中。我不确定我的冲突在哪里进行。库尔特的回答也出现了同样的问题。 –

0
if($(this).val().indexOf("")) 

if($(this).val.indexOf("")) 

尝试使用indexOf,看看用户输入的东西

3

你每场会在(与each功能)。当这个值为空时,你隐藏链接,但是你继续运行其他字段。当值为空时,应该放置'break'语句,以便进一步处理停止。通过所有字段并维护一个布尔参数甚至会更好。在循环之后,您根据布尔参数隐藏或显示链接。

像这样:

$('#showlink').hide(); // Assume form is incomplete 

$('form#form_id').change(function(e) { 
var complete = true; // Set start of boolean expression 

$(":input").each(function() { 
    complete = complete && $(this).val() !== ""; //If val is empty, the whole expression after the iteration will evaluate to false 
}); 

if(complete) { 
    $("#showlink").show(); 
} 
}); 
+0

这一个似乎在小提琴中工作,但不适用于我的代码。我可能会在其他地方发生冲突...... http://jsfiddle.net/SP8TC/ –

+0

你能给更多的信息吗?控制台日志中是否有任何内容? –

0

除了@ asymptoticFault的回答其他变种 - 使用一个变量来保存,如果该链接应被隐藏或不:这里

var $allInputs = $("input:text"), 
    $button = $("#btnSubmit").hide(); 

$allInputs.change(function(){ 
    var isEmpty = $allInputs.filter(function(){ 
        return ($(this).val()==""); 
       }); 
    $button.hide(); 
    if(isEmpty.length == 0){ 
     $button.show(); 
    } 
}); 

工作小提琴:

$('form#form_id').change(function(e) { 
    var should_hide = false; 
    $(":input").each(function() { 
    if($(this).val() === ""){ 
     should_hide = true; 
     return false; // do not process each any more 
    } 
    }); 
    if (should_hide) { 
    $("#showlink").hide(); 
    } else { 
    $("#showlink").show(); 
    } 
});