通过按“输入”来发送表单。键

时间:2018-01-22 14:07:11

标签: javascript jquery

我想在推送' Enter'之后通过AJAX发送表格。按钮。我找到了不同类型的解决方案,但我之前做过,它的工作方式如下:

<form method="POST" id="newName" action="javascript:void(null);" onsubmit="editName()">
   <input type="text" id="input_{{ projectName.project_id }}" name="new_name" class='input_new_name'
   data-target="{{ projectName.project_id }}" placeholder="{{ projectName.project_name }}" >
   <input type="submit" hidden>
</form>

我的JS代码:

function editName() {
    var msg = $('#newName').serialize();
    $.ajax({
        type: 'POST',
        url: '../edit/editprojectname',
        data: msg,
        success: function() {
            window.location.reload();
        }

    });
}

我哪里错了?

哦,我正在圈中使用它!

{% for projectName in namesOfProjects %}
    <form action="" method="post">
        <tr>
            <td>{{ projectName.project_id }}</td>
            <td>
                <button class="show-hide-field toggle_button" id="{{ projectName.project_id }}">{{ projectName.project_name }}</button>
                <form method="POST" id="newName_{{ projectName.project_id }}" action="javascript:void(null);" onsubmit="editName()">
                    <input type="text" id="input_{{ projectName.project_id }}" name="new_name" class='input_new_name'
                           data-target="{{ projectName.project_id }}" placeholder="{{ projectName.project_name }}" >
                    <input type="submit" hidden>
                </form>
            </td>
            <td>
                <button  id="delete" class="btn btn-danger">Delete</button>
            </td>
        </tr>
    </form>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

更改HTML - 删除输入按钮和部分表单属性。

<form method="POST" id="newName">
   <input type="text" id="input_{{ projectName.project_id }}" name="new_name" class='input_new_name'
   data-target="{{ projectName.project_id }}" placeholder="{{ projectName.project_name }}" >

</form>

在页面加载时,配置表单以识别回车键

window.onload = function() {
   var form = document.getElementById('newName');
   form.addEventListener('keyup', function(e){
     if (e.keyCode === 13) {
        editName();
     }
   });
};