【问题标题】:textarea expanded with jquery, not submitting the form when i click the submit button用jquery扩展的textarea,当我点击提交按钮时不提交表单
【发布时间】:2012-05-13 20:57:03
【问题描述】:

我希望按钮在文本区域展开时提交表单。我该怎么做呢?

问题是当我点击表单中的Post按钮时,当textarea展开时,并没有提交表单,而是缩小了,我需要在它变小的时候再次点击,提交表格。

目前为了提交帖子,我需要在 textarea 未展开时单击帖子按钮。

HTML

<form method='POST' action='elsewhere.php'>
    <textarea id="textarea" style="width:550px; height:25px;"></textarea>
    <input class="btn" type='submit' value='Post'/>                             
</form>

jquery

目前,当我单击文本区域时,高度会扩大,而当我单击其他地方时,它会缩小。当我点击发布按钮时,当 textarea 展开时它不会提交帖子,而是将 textarea 缩小回来。

$('#textarea').click(function(){
    $(this).css('height','100px')
    $(this).html('');
    $(this).blur(function(){
        $(this).css('height','25px')

    });
})

【问题讨论】:

  • 我认为这是一些与z-index 相关的问题。尝试将position: relative; z-index:1 提供给提交按钮。
  • jsfiddle 用于测试
  • @arboles,你试过我的建议了吗!!最近我遇到了类似的问题。
  • @itsnotme 你的建议在哪里?
  • 这是第一个评论和最后一个答案...

标签: javascript jquery html forms post


【解决方案1】:

如果您正在提交表单并重定向到另一个页面,您只需要让按钮保持足够长的时间来注册点击,超时就可以解决这个问题:

$('#textarea').on({
    focus: function() {
        $(this).css('height','100px').html('');
    },
    blur: function() {
        var self = this,
            T = setTimeout(function() {$(self).css('height','25px') }, 200);
    }
});

FIDDLE

如果将它与 Ajax 一起使用,而不是重定向,并且要使 textarea 不响应按钮上的单击,您可以使用变量来跟踪单击了哪个元素,并且与上面的操作有些相同:

var elm;

$('.btn').on('click', function(e) {
    elm = e.target;
    e.preventDefault();
    //do ajax stuff
});

$('#textarea').on({
    focus: function() {
        $(this).css('height','100px').html('');
    },
    blur: function() {
        var self = this,
            T = setTimeout(function() {
                if ($(elm).attr('class') != 'btn') $(self).css('height','25px');
            }, 200);
    }
});

FIDDLE

【讨论】:

  • 我可以将两个答案都标记为正确吗?因为除了其他方法之外,这种方法也有效。自从他第一个回答以来,我将另一个标记为答案。
  • 这取决于你,但是另一个答案是错误的,它与位置或z-index无关,textarea没有与按钮重叠,但是模糊功能发生得太快以至于点击按钮未注册,因为按钮在您实际单击之前移动。
  • @arboles。是的,看起来这应该是公认的答案。
【解决方案2】:

我认为这是一些与 z-index 相关的问题。尝试将position: relative; z-index:1; 提供给提交按钮。

如果您为textarea 或其任何祖先设置了z-index,则将该值加一并将其设置为按钮。

按钮有可能在增加其高度的同时被文本区域覆盖。 你也提到了,while the textarea is expanded it doesnt submit the post。可能是因为按钮重叠了。

更新:

我得到它之后

问题是当我点击表单中的Post按钮时,当textarea展开时,并没有提交表单,而是缩小了,我需要在它变小的时候再次点击, 提交表单。

$('#textarea').click(function(){
$(this).css('height','100px')
$(this).html('');
$(this).blur(function(){
    if(this.value === ''){
        $(this).css('height','25px')
    }

});
});

【讨论】:

  • 有人能解释一下 -1 吗?
  • @arboles。不,这家伙试图帮助你。
【解决方案3】:

前几天我遇到了类似的问题,发生的事情是 textarea 上的 blur 事件发生在浏览器考虑到按钮上的 click 事件之前。

因此,按顺序,我点击按钮,然后浏览器在 textarea 上触发 blur 事件,缩小它并移动按钮,然后浏览器考虑点击,什么也不做,因为没有长了我点击的按钮。

不过,我并没有直接解决问题,而是决定仅在 textarea 不为空时才缩小它(在 blur 事件中添加一些 this.value == this.defaultValue || this.value == '' 测试)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-26
    • 2016-01-11
    • 1970-01-01
    • 2016-12-31
    • 2013-03-24
    • 1970-01-01
    • 2020-12-03
    • 2019-01-03
    相关资源
    最近更新 更多