Javascript onblur & onclick function saves record multiple times - javascript

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

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

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

Related

How to make button disable with error message from response and after one click using angular2

I have a send Button, that contains 2 Api in it.
So, if the input box is empty then send the button is disabled.
Now i want 2 conditions to work,
1. if i get an error message from the response saying
Email-Id you provided is not exist in medicamind account,
then my send button must be disabled untill Correct email is given.
After giving Email-Id and click on save button, it must get disabled after one click.
If i edit again on input box then it must be enabled or it must be in disabled state.
Use the attr disabled of the button :. If you get an error put it to true and when the correct one is received put it to false.
For the second case just put (click)="generateEmailOtp(enterSms,enterEmail); booleanVar = false" must be enought. I hope it could help you!
You can have multiple events, I think you know it. So you need to validate two things:
1- Validate Email;
2- OnClick you call your method which returns something but once it's clicked you need to disable it again.
You can validate email as the user's type, since you are using template driven form you use keyup event to validate your email using regex. Like this:
<!-- HTML File -->
<input
type="text"
[(ngModel)]="inputData"
(keyup)="keyUpMethod()" >
<button
[disabled]="checkBtn"
(click)="apiCallMethod()">
// .ts File
inputData: string; // input Data
checkBtn: boolean = false; // Declare it initially as false
// This method fires when the user types
keyUpMethod() {
if (this.validateEmail(this.inputData)) {
this.inputData = true; // this enables your button
} else {
// if you want to add any exception, it goes here
}
}
// for validation of email
validateEmail(email) {
// validate your email here
return either true or false;
}
// this is will trigger when the user clicks on the button
apiCallMethod() {
this.inputData = false; // Disable the button again
// your button is disabled and you are already in this method, now you can do the
// other stuff here
}

jQuery disable double click prevention breaking functionality of a PHP function in a form

I have a jquery bug that I cant solve - hoping for help with a solution. Dont know if it is browser bug related (probably not), jQuery related, or Yii (our backend) related - but I need to try to solve it with the jQuery portion. Code at bottom of message.
Requirement: Disable accidental double submissions on forms.
Current Solution: Check for form submission state through a delegate and when the DOM form state changes to submit - append the disable attribute to the form submit button to prevent accident double form submission.
jQuery double click disabler:
$( document ).ready(function() {
$('html').delegate('form', 'submit', function() {
$(this).find(':submit').attr('disabled', true);
});
});
Problem: This works perfectly on every part of the CRM we are developing EXCEPT for a single timekeeper (clock in/clock out) feature. With the timekeeper the form has two submit buttons (one for clock in, one for clock out). Only one submit button shows at a time (Either "In" or "Out". When you click the button - it submits the form and changes the submit button to the other state by checking a session var to determine what state it is in and determines which of the two submit buttons are to be displayed. Problem is if you click it, the form appears to submit, but the state don't change. If you click it really fast a few times you can get it to change state. I suspect this is a timing or order of operations issue, but I have no idea how to fix it. The fix MUST be done on the front end, so here is the code (both the PHP being impacted and jQuery double click prevention). Perhaps a different method of disabling double submissions may work, please post your solution if you have one to try. Commenting out the current jQuery allows the form to function as designed. What might be causing this, and how might I change the jQuery double click prevention to solve it?
On page PHP for the time clock:
<form action = "<?=$clockUrl?>" method = "post" >
<input type = "hidden" name = "previousUrl" value = "<?=$currentUrl?>">
<?php if ($sessionVar->timeclockin) {?>
<input type = "submit" name = "submit-clockout" value = "Out">
<class="clock-time" ><?=$sessionVar->timeclockin?></class="clock-time">
<?php } else {?>
<input type = "submit" name = "submit-clockin" value = "In">
<?php }?>
</form>
Thank you for pointing me in the right direction Tyler! I was able to fix the issue with the following alteration to my script.
function do_nothing() {
console.log("click prevented");
return false;
}
$('html').delegate('form', 'submit', function(e) {
$(e.target).find(':submit').click(do_nothing);
setTimeout(function(){
$(e.target).unbind('click', do_nothing);
}, 10000);
});
Update 1:
If you are looking to prevent the button from being pressed twice then inside of your onclick or submit function, you should use something similar to the following:
$('#yourButton').prop('disabled', true);
If the page then redirects then you won't have to undo this. If it does, then do the opposite by changing true to false.
The submit function should instead disable the submit button until it either returns or fails.
An alternative is to use a lambda style function and replace it temporarily with an empty function until the request returns or fails.

form action call button

In a form, i have a button and an image... when i click on image, form action is called, that work... but when i click on the button action is not called.
Is there a specific thing to do for a button?
js
$('#formUser').submit(function() {
$(this).attr("action", "/secure/downloaduserinfo/" + reportName);
});
$('#formUser').submit(function() {
$(this).attr("action", "/secure/deleteuser/" + reportName);
});
web part
<button type="button" id="deleteUserButton${statusReport.count}"></button>
<input id="downloadUserButton${statusReport.count}" type="image"/>
type="button" elements are not submit buttons, they exist solely to run client side code.
If you want to submit the form, use type="submit" (or don't specify a type attribute at all, submit is the default).
That said, I'd avoid the dependancy on JavaScript. Give the buttons and name and a value and use that on the server to determine if you want to download or delete.
The input of type "image" is similar to "submit", it does submit your form, that's why your submit handler is working. While the input of type "button" does not submit the form, it just looks like a button.
You have 2 submit listeners for the same element so every time the #formUser is submitted it uses the first submit listener it finds.
You can use the onclick listener and tie it to the specific element being clicked.
I'm not sure how the templating system it looks like you're using is tied in but I'd use a class instead of the id.
<button type="button" class="delete-user-button" id="deleteUserButton99">Delete</button>
<img src="http://placehold.it/200x200" class="download-user-button" id="downloadUserButton99"/>
<script>
$('.delete-user-button').click(function() {
// store object that was clicked
var obj = $(this);
// set that objects action attribute
obj.attr("action", "/secure/deleteuser/" + obj.attr('id'));
// show the action attribute's value
alert(obj.attr('action'));
});
$('.download-user-button').click(function() {
// store object that was clicked
var obj = $(this);
// set that objects action attribute
obj.attr("action", "/secure/downloaduserinfo/" + obj.attr('id'));
// show the action attribute's value
alert(obj.attr('action'));
});
</script>
Here's a fiddle that demonstrates manipulating the object by the click listener: http://jsfiddle.net/chapmanc/HHfQT/2/

Form submit/update onclick

I must rebuild a form, there are two buttons, one is for increasing the value of an input and second for decrease the value, and I must delete submit button and update form always if I click on increase or decrease, i have tried this with jquery onchange:
I have read also this: http://api.jquery.com/submit/
$("#increaseButton").change( function() {
$("#quantityForm").submit();
});
I can't edit form, because I must work only with submit, is that possible?
I think a click would be better here:
$('#increaseButton').on('click', function() {
increaseValue(); //call a function to increase the value
$("#quantityForm").submit(); //submits the form
});
what is #increaseButton? is it just a link? or actual
<input type="button" />
I don't think buttons can have a "change" event attached to them

jQuery validation - multiple groups

Im designing a user control that has the following:
a textbox called 'AddressInput'
a google maps plugin
a linkbutton
a textbox for the marker title called 'MarkerTitleInput'
a "Submit" button
The problem is this:
When the linkbutton is clicked, I need to validate that AddressInput was completed, but nothing else
When the submit button is clicked, I need to validate that AddressInput and MarkerTitleInput were both completed.
So my first two problems are:
1) How do i validate certain fields from a linkbutton, without submitting the form
2) How do i validate all fields from the form being submitted
My other problem is that when the linkbutton is clicked, my code runs a lookup against Google's Geocode to get an address. I was going to create an additional validation method to handle when an address is not found, but using a validator means the json request is sent everytime a key is pressed, which is too much - i only want the validation to run when the linkbutton is clicked. I have tried (selector).validate({ onkeyup:false }) with no avail. Is it perhaps possible to manually set whether the .valid() method thinks the form is valid?
Thanks
Al
$("form").validate({
groups:{
pg1:"_Phone1 _Phone2 _Phone3",
pg2:"dob_month dob_day dob_year"
},
errorPlacement:function(error, element){
if(element.attr("name")=="_Phone1"|| element.attr("name")=="_Phone2" || element.attr("name")=="_Phone3"){
error.insertAfter("#_Phone3")
}
else if
(element.attr("name")=="dob_month"|| element.attr("name")=="dob_day" || element.attr("name")=="dob_year"){
error.insertAfter("#dob_year")
}
else
error.insertAfter(element);
},
});
});
Give each of the two buttons a unique class (for ease of targeting in jQuery).
Give each class an OnClick event.
Validate in the OnClick event.
If the validation succeeds, return true.
Else return false.

Categories

Resources