简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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