简体   繁体   English

如何正确地将单击的按钮属性值传递给表单提交事件?

[英]How to properly pass clicked button attribute value to form submit event?

I have a function that listens to a click and form submit from the same button and submits a PUT request as per below: 我有一个函数,可以监听来自同一按钮的click和表单submit ,并按照以下方式提交PUT请求:

The button: 按钮:

<input type="submit" id="amendProj" placeholder="45" class="btn btn-dark" value="Save Changes">

The function: 功能:

// PUT amend project function
$(document).on('click', '#amendProj', function () {

    // fetch clicked button placeholder value
    var fired_button = $(this).attr('placeholder');

    // await default validation before form submission
    $(document).on("submit", "#collapse" + fired_button, function (e) {

        e.preventDefault();

        // show loading spinner
        document.getElementById("spinner").hidden = false;

        //collect form data
        var params = {

        projectId: fired_button,
        projectManager: $("#selectionMan" + fired_button + " option:selected").text(),
        projectOwner: $("#selectionOwn" + fired_button + " option:selected").text(),
        predictedLaunch: document.querySelector('#preDate' + fired_button).value,
        actualLaunch: document.querySelector('#actDate' + fired_button).value,
        predictedCompletion: document.querySelector('#precomDate' + fired_button).value,
        actualCompletion: document.querySelector('#actcomDate' + fired_button).value,
        predictedCost: document.querySelector('#preCost' + fired_button).value,
        actualCost: document.querySelector('#actCost' + fired_button).value,
        price: document.querySelector('#charge' + fired_button).value,
        projectTitle: document.querySelector('#projTitle' + fired_button).value,
        projectDescription: document.querySelector('#projDescribe' + fired_button).value,
        requestor: document.querySelector('#projRequestor' + fired_button).value,
        requestorEmail: document.querySelector('#requestorEmail' + fired_button).value,
        requestorTel: document.querySelector('#requestorTel' + fired_button).value,
        status: $("#projStatus" + fired_button + " option:selected").text()
        }

        // Create XHR Object and send
        var xhr = new XMLHttpRequest();
        xhr.open('PUT', 'http://link/resource/api/Projects/' + fired_button, true)
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(JSON.stringify(params));

        // Handle errors
        xhr.onload = function () {

            if (this.status == 204) {

                // hide loading spinner
                document.getElementById("spinner").hidden = true;
                alert("Changes saved successfully!");
                console.log(this.status + ' Changes submitted successfully!');

            }

            else  {

                // hide loading spinner
                document.getElementById("spinner").hidden = true;
                alert("Your submission failed. Please try again");
            }
        }
    });

});

Now I have default HTML validation in place with required . 现在,我已使用required进行了默认的HTML验证。 When I leave a field blank and click the button the browser responds with a default validation message. 当我将字段保留为空白并单击按钮时,浏览器将响应并显示默认验证消息。 I correct my input, click the button again and my function is executed twice or even more depending on how many times I failed to pass validation. 我更正了我的输入,再次单击该按钮,我的功能被执行两次甚至更多,这取决于我通过验证的次数失败。 Thus this results in an alert box being shown twice or more times after successful execution as per my code. 因此,按照我的代码,这将导致警报框在成功执行后显示两次或多次。 How do I refactor the code so this behaviour does not happen? 如何重构代码,这样就不会发生这种情况? I'm new to jquery and js so might be missing something. 我是jquery和js的新手,因此可能缺少一些东西。

It feels like when I fail validation one time the function is still running and waiting to be executed. 感觉好像一次验证失败时,该功能仍在运行并等待执行。 And when I click the button again to submit after correcting my mistakes it obviously calls the function again and executes coupled with the one that didn't finish executing because validation was unsuccessful. 当我在更正错误后再次单击该按钮提交时,它显然会再次调用该函数并与未完成执行的函数一起执行,因为验证未成功。 Really appreciate if an expert could lend a hand, thanks. 非常感谢专家可以帮忙,谢谢。

It looks like you are adding a submit handler to collapse45 with every click. 似乎您每次单击都在塌陷45中添加一个提交处理程序。 You can clear any existing handler by adding the line: 您可以通过添加以下行来清除任何现有处理程序:

$(document).off("submit", "#collapse" + fired_button);

before the line: 前行:

$(document).on("submit", "#collapse" + fired_button...etc

Don't know if it's the best solution but it should work 不知道这是否是最好的解决方案,但它应该可以工作

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

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