Reputation: 2659
I have two functions now that each start on a different event (click
and blur
) both start when interacting with different elements. Is there a way to combine the two? So when clicking the button, the function fires and when losing focus on an input (blur
) the same function starts without sending an ajax call twice? So clicking an input should not start the function, only clicking the button.
These are my functions as they are now:
$("#account-details").on("click",".save-button",function(e){
e.preventDefault();
// if($('#registerform')[0].reportValidity()){
accountform = $(".account-form").serialize();
$.ajax({
type:'post',
url:"includes/updateaccount.php",
data:({accountform: accountform}),
success:function(data){
var obj = JSON.parse(data);
for (var i = 0; i < obj.length; i++) {
var status = obj[i].status;
var field = obj[i].field;
if(status == 'error'){
var message = obj[i].message;
$( 'input[name="' + field + '"]' ).addClass('invalid-input');
var errorveld = $( 'input[name="' + field + '"]' );
$( 'input[name="' + field + '"] + div').remove();
errorveld.after('<div class="inputerror">' + message + '</div>');
}else if(status == 'success'){
$( 'input[name="' + field + '"] + div').remove();
$( 'input[name="' + field + '"]' ).removeClass('invalid-input');
}
}
}
});
// }else{
//
// }
});
$("#account-details").on("blur","input",function(e){
e.preventDefault();
// if($('#registerform')[0].reportValidity()){
accountform = $(".account-form").serialize();
$.ajax({
type:'post',
url:"includes/updateaccount.php",
data:({accountform: accountform}),
success:function(data){
var obj = JSON.parse(data);
for (var i = 0; i < obj.length; i++) {
var status = obj[i].status;
var field = obj[i].field;
if(status == 'error'){
var message = obj[i].message;
$( 'input[name="' + field + '"]' ).addClass('invalid-input');
var errorveld = $( 'input[name="' + field + '"]' );
$( 'input[name="' + field + '"] + div').remove();
errorveld.after('<div class="inputerror">' + message + '</div>');
}else if(status == 'success'){
$( 'input[name="' + field + '"] + div').remove();
$( 'input[name="' + field + '"]' ).removeClass('invalid-input');
}
}
}
});
// }else{
//
// }
});
I found another question with this answer:
$('#element1, #element2').on('click change', function(event){
var $this = $(this);
if (($this.is('#element1') && event.type === 'change') || ($this.is('#element2') && event.type === 'click')) {
myFunction();
}
});
The problem is my elements are children of a parent (#account-details
). How can it be done?
Upvotes: 0
Views: 55
Reputation: 225
Using the answer you found:
$('#account-details .save-button, #account-details input').on('click blur', function(event){
var $this = $(this);
if (($this.is('#account-details input') && event.type === 'blur') || ($this.is('#account-details .save-button') && event.type === 'click')) {
myFunction();
}
});
I hope this is the solution that you are looking for
Upvotes: 1