This question already has answers here:
Is there an “after submit” jQuery option?
                            
                                (4个答案)
                            
                    
                4年前关闭。
        

    

我有一个文本字段和一个提交此文本字段的按钮,看起来像

<form action="/library" method='POST'>
    {{ form_add_library_category.name(size=80, class="form-control", id="new_category_field", placeholder='New category', onkeyup="stoppedTyping()", style="height:35px;width:205px;display:inline;") }}
    <button type="submit" class="btn btn-primary add_button" id="add_category" style="display: inline;margin-top:-3px;height:35px">Add</button>
</form>


提交文本字段后,我想将文本字段的值设置为空字符串并禁用按钮。我用javascript

<script type="text/javascript">
$(document).ready(function(){
    $("#add_category").click(function(){
        document.getElementById('new_category_field').value = '';
        document.getElementById('add_category').disabled = true;
    });
});
</script>


因此单击该按钮后,表单将自动提交。并且javascript部分会删除文本字段中的值并禁用按钮。但是,我注意到此设置有两个可能的结果。可能是JavaScript速度更快,在这种情况下,文本字段设置为空值,并且该空字符串与表单一起提交。还是表格速度更快,在这种情况下,一切都会按预期进行。有没有一种方法可以确保在提交表单后始终执行javascript函数?
谢谢
卡尔

编辑:在当前答复的基础上,我将我的javascript函数更改为

<script type="text/javascript">
$(document).ready(function() {
    $('#add_category_form').submit(function(e) {
        e.preventDefault();
        this.submit();

        setTimeout(function(){ // Delay for Chrome
            $('#new_category_field').val('');
            $('#add_category').prop('disabled', true);
        }, 100);
    });
});
</script>


这样可以防止表单在提交之前被清空。尤其是Chrome浏览器似乎在提交之前清空了表单,因此似乎需要超时...即使我认为它不是很好。无论如何,设置为空字符串的值仍然不起作用?

最佳答案

的HTML

<form action="/library" method="POST" id="form">
...


jQuery的

$(document).ready(function() {
    $('#form').submit(function(e) {
        e.preventDefault();
        this.submit();
        $('#new_category_field').val('');
        $('#add_category').prop('disabled', true);
    });
});


未经测试,但我认为它应该工作。

编辑:以防万一,停止默认操作,提交表单,然后清除值。

09-11 19:11
查看更多