簡體   English   中英

單擊保存按鈕后如何提交表單?

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

這是我的一些代碼來自文件名settings.handlebars ,輸入框被禁用,直到我單擊編輯按鈕。 在輸入字段中添加一個值后,如果我單擊保存按鈕,它應該將該值傳遞給我的 js。 代碼如下:

<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>

這是我在同一個文件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>

這是我的main.js文件。 當我單擊保存按鈕時,這應該可以工作,但沒有任何反應:

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")
});

我想我在 jQuery 上遺漏了一些東西,但我不知道它是什么。 謝謝!

嘗試添加e.preventDefault(); 在你的.click()里面。 它目前阻止您提交表單。

如果事件可取消,則需要添加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