简体   繁体   English

单击保存按钮后如何提交表单?

[英]How can I submit the form after clicking the save button?

This is some of my code from the file name settings.handlebars , the input box are disabled until Ii click the edit button.这是我的一些代码来自文件名settings.handlebars ,输入框被禁用,直到我单击编辑按钮。 After adding a value in the input field it supposed to pass the value to my js if I click the save button.在输入字段中添加一个值后,如果我单击保存按钮,它应该将该值传递给我的 js。 The code is below:代码如下:

<form method="post" action="/save">
   <input type="text" name="username" id="username" class="form-control" value="{{username}}">

   <button type="submit" class="btn btn-success" value="save" id="save">Save Changes</button>
   <button type="button" class="btn btn-secondary" value="cancel" id="cancel">Cancel</button>
   <button type="button" class="btn btn-info" value="edit" id="edit">Edit Info</button>

</form>

This is my jQuery in the same file settings.handlebars .这是我在同一个文件settings.handlebars中的 jQuery。

<Script>
    $('#edit').click(function () {
        $(this).hide();
        $('#save, #cancel').show();
        $("#target :input").prop("disabled", false);
    });

    $('#cancel').click(function () {
        $('#edit').show();
        $('#save, #cancel').hide();
        $("#target :input").prop("disabled", true);
    });

    $('#save').click(function () {

        $(this).hide();
        $('#cancel').hide();
        $('#edit').show();
        $("#target :input").prop("disabled", true);

    });
    $("#target :input").prop("disabled", true);
</Script>

And this is my main.js file.这是我的main.js文件。 When I click the save button this is supposed to work but nothing happens:当我单击保存按钮时,这应该可以工作,但没有任何反应:

app.post('/save', function (req, res, next) {

    let configObj = {
        username: req.body.username
    }

    fs.writeFile('config.json', JSON.stringify(configObj), (err) => {
        if (err) {
            res.send("<h4>ERROR</h4>")
        }
    });
    res.redirect("/settings")
});

I think I missed something on my jQuery but I don't know what it is.我想我在 jQuery 上遗漏了一些东西,但我不知道它是什么。 Thank you!谢谢!

Try adding e.preventDefault();尝试添加e.preventDefault(); inside your .click() .在你的.click()里面。 It is currently preventing your form from submitting.它目前阻止您提交表单。

You need to add prevenDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.如果事件可取消,则需要添加prevenDefault()方法取消该事件,这意味着不会发生属于该事件的默认操作。

<script>
    // I have added only for the save function
    $('#save').click(function (e) {
        e.preventDefault();
        $(this).hide();
        $('#cancel').hide();
        $('#edit').show();
        $("#target :input").prop("disabled", true);    
    });
    $("#target :input").prop("disabled", true);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM