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>

我在这里错过了什么吗?

4

5 回答 5

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();
 }
});
于 2013-08-24T22:10:27.987 回答
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函数来迭代整个文档中的所有输入,而不仅仅是表单,并且链接将根据它们的值为每个输入显示和隐藏,因此最终链接将仅基于可见或隐藏在迭代中检查的最后一个值。

于 2013-08-24T22:22:39.247 回答
0

除了@asymptoticFault 的答案之外的其他变体 - 使用变量来保存链接是否应该隐藏:

$('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();
  }
});
于 2013-08-24T22:33:17.603 回答
0
if($(this).val().indexOf(""))

或者

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

尝试使用indexOf查看用户是否输入了某些内容

于 2013-08-24T22:09:20.297 回答
0

你可以这样做:

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

在这里工作小提琴:http: //jsfiddle.net/QwvtL/4/

于 2013-08-24T23:38:07.623 回答