简体   繁体   中英

Javascript onblur & onclick function saves record multiple times

I have one Javascript function named " saveForm() " from which I am saving the records in the database.

My form has one button as 'Save in draft' which saves the record in draft mode. On this button, there is onclick event which calls above javascript " saveForm() " function.

Now, I have a feature about autosave the record which calls javascript above " saveForm() " function on every onblur event of the form field.

Now, the scenario is when I fill one of the fields & directly clicks on 'Save in draft' button, it saves the records multiple times as both( onblur & onclick ) events called parallel.

Onclick :

<input type="button" class="btn" id="draftsave" value="Save in draft" onclick="javascript: saveForm(this.form.id, 'draft');" />

Onblur :

jQuery(document).delegate(":input[type!='button']", "blur", function() {            
    saveForm(this.form.id, "draft");
});

HTML Form

okay so if you want this functionality(but you can just keep yout submit associated to onChange) just send a boolean filed on change event like

<input type="text" onChange="someFunction(true);">

Now you can take a global boolean variable and update its value with the value of onChange boolean param.

boolean isOnChangeCalled=false;//global variable

function someFunction(isOnchange)
{
this.isOnChangeCalled=isOnchange
}

and in case of onClick just check if this boolean ie isOnChangeCalled is set to true only then perform a onClick event otherwise prompt user that form is already saved

To verify in back end In case data is already submitted and user clicks submit button then then just check if the data is already updated in database by comparing two objects but that is an extra overhead and return appropriate reponse in case data is already there

UPDTATE you can maintain a clone of your form object and before your onClick event you can compare both objects and if they are same just prompt user the relevant message

You can do something like below or you can check before inserting in database but in that case it will make multiple backend calls, its better to keep a check in front end while making the backend call, so you can try the below code and see if it solves your problem:

 var clicked; $("#draftsave").click(function() { clicked = true; }); jQuery(document).delegate(":input[type!='button']", "blur", function() { if (!clicked) { saveForm(this.form.id, "draft"); } else { //do something } }); 

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