javascript - How can I loop through a list of form ID's and add a submit handler to each? -


i have website containing lot of different contact forms. want keep array of id's (and other related settings) can loop through them , add submit handlers each one.

the problem last form in array seems handler attached it.

list of forms:

forms = [     {id: '#contact-form-1', ...},     {id: '#contact-form-2', ...} ] 

how i'm trying add submit handlers:

for (i in forms) {     $(document).on('submit', forms[i].id, function(){         // validation, send email etc.     } } 

is $(document).on() right way approach this? have tried $(forms[i].id).submit(); same outcome; last form in list gets bound to.

might want other way round.

/* listen submit forms */ $('form').on('submit', function() {    /* id of 1 */    var _id = $(this).attr('id');      /* conditions on _id */   )); 

so objects :

var formids = {       formidone: { func : function() { alert('called form id one'); }},       formidtwo: { func : function() { alert('called form id two'); }}     }; 

then say:

$('form').on('submit', function() {    /* id of 1 */    var _id = $(this).attr('id');      /* call form function associated form id */     formids[_id].func();  )); 

a few ways this, depends how want organise code , little easier defining listener once


adding edit : not explained going wrong in original code - context of i not retained correctly ( hinted in comment )

the solution make use of function :

function makehandler (index) {  $('#'+forms[index].id).on('submit', function(){... }); }  (i in forms) {  makehandler(i); } 

this best place problems around making functions in loop - how fix jslint error 'don't make functions within loop.'?


would still favour using one handler above, easier maintain / read ( imo )


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -