如何在textarea onblur上保持提交按钮可见和可执行

时间:2010-05-12 03:46:10

标签: jquery blur

我有一个<div id="comment_posting_holder">标签,其中包含一个包含两个元素的表单:textarea框和提交按钮。

如果我单击“OTHER”而不是“提交”按钮,我希望div标签(包含textarea和submit按钮)消失。我从下面的代码开始。因此,在从textarea离开焦点时,我可以使div标签消失。

问题是如果div消失,提交按钮也会消失,这意味着我无法提交表单!我该如何解决这个问题?

有什么建议吗?谢谢!

** Facebook用它的评论做到了这一点。如果您单击“发表您的评论...”字段,则会出现textarea,然后除非您按下提交按钮,否则它将在失去焦点时消失。

$('textarea').blur(function() {
     $('#comment_posting_holder').hide();
});

3 个答案:

答案 0 :(得分:3)

如果你想要像facebook这样的实现,你需要检查是否有人在文本框中写了一些内容。

您可以看到我的回答有效here

HTML

<div>
   <textarea class="comment_empty">Write a comment</textarea><br />
   <input type="submit" id="submit" value="Submit" style="display: none" />
</div>

的jQuery

$(document).ready(function(){
    var submit = $("#submit");

    $("textarea").blur(function() {
        if ($(this).val() == "") {
            $(this).val("Write a comment")
                   .removeClass("comment_filled")
                   .addClass("comment_empty");
            submit.hide();
        }
    }).focus(function() {
        if ($(this).val() == "Write a comment") {
            $(this).val("")
                   .removeClass("comment_empty")
                   .addClass("comment_filled");
            submit.show();
        }
    });
});

一些CSS

.comment_empty {
   color: gray;
   height: 30px;
}

.comment_filled {
   color: black;
   height: 100px;
}

答案 1 :(得分:3)

我理解你想要的东西:
如果用户单击任意位置,并且单击的元素不是提交按钮,则隐藏div。

执行此操作的代码:

$(document).ready(function() {
  $(document).click(function(event) {
    if (event.target.id == "idOfSubmitButton") {
      //user clicked the submit button (make sure to give it an ID)
      //if you wanted to be really hardcore, you could submit the form here via AJAX
    }
    else {
      //user clicked anywhere on the page but the submit button
      //here you'd want to check and make sure someone has actually typed
      //something in the textarea, otherwise this will happen for every
      //click on a hyperlink, button, image, et cetera on the page
      $('#comment_posting_holder').hide();
    }
  });
});

答案 2 :(得分:1)

由于代码中的语法错误,导致无法正常工作。除了缺少单引号之外,你所看到的只要是在实际发射的事件中。试试这个:

$(document).ready(function(){
    $('textarea').blur(function() {
        $('#comment_posting_holder').hide();
    });
});