jQuery - Multiple events to trigger same function but with different elements -


jquery snippet:

function main_call(){ jquery("#user_registration").on('submit',function(event) {      load_product_serial(); }); jquery("#reg_submit").on('blur',function(event) {     load_product_serial();  });  }   function load_product_serial(){         var result = [];         var prod_serial = jquery('#reg-product-serial').val(); //fetch input value         jquery.ajax({         type: "get",          url: ajaxurl,         async: false,         datatype : "json",         contenttype: 'application/json; charset=utf-8',         data : {action: "get_product_serial"},         //cache: false,              success: function(data){                  result = data;                 if( jquery.inarray( prod_serial, result ) < 0 ){                     jquery( "#invalid_dialog" ).dialog({                     width: 350,                     modal: true,                     resizable: false,                     dialogclass: 'no-close success-dialog',                     buttons: {                       ok: function() {                         jquery( ).dialog( "close" );                       }                     }                   });                     jquery( "button.ui-dialog-titlebar-close" ).hide();//hide close button                     event.preventdefault();                     return false;                  }else{                     alert('success');                     //jquery( "#valid_dialog" ).dialog();                     return true;                 }             },             error: function() {                 alert('unexpected error occured. please try again.');             }         });         //}); } 

here need call function when user clicks on submit button event (reg-product-serial) or when user changes input value onblur event (reg-product-serial)

i can bind using .on() multiple events element here not same.

$('#element').on('keyup keypress blur change', function() {     ... }); 

this not duplicate not using 1 common element 2 different elements same function.

use more 1 line:

$('#element').on('submit',function() { load_product_serial(); }); $('#element2').on('keypress blur change',function() { load_product_serial(); }); 

also, fyi, don't use click event bind function submit button click when want bind submit event of form itself.

edit

regarding comment below event not defined error, don't forget pass in event object argument:

function load_product_serial(event) {   ....   event.preventdefault();   .... }  $('#element').on('submit',function(e) { load_product_serial(e); }); $('#element2').on('keypress blur change',function(e) { load_product_serial(e); }); 

Comments

Popular posts from this blog

gcc - MinGW's ld cannot perform PE operations on non PE output file -

timeout - Handshake_timeout on RabbitMQ using python and pika from remote vm -

c# - Search and Add Comment with OpenXML for Word -