javascript - Concatenating a variable as the jQuery val() argument? -
i'm trying set value attribute of input (a hidden input in form) using jquery val() function. idea concatenate name of variable , pass argument function, doesn't work expected. code in question in last line:
$(document).ready(function(){ var hash = document.location.hash; var turismossid = "1c0f8e3ec28b09f9487140930a0c0b73"; var comercialessid = "b31150acd348f775785b7c4a7398a3c6"; if (hash === "#turismos") { activatab("turismos"); $('#js-sid').val(turismossid); } else { activatab("comerciales"); $('#js-sid').val(comercialessid); } $('#js-turismos-btn').on('click', function(){ activatab("turismos"); document.location.hash = "turismos"; }); $('#js-comerciales-btn').on('click', function(){ activatab("comerciales"); document.location.hash = "comerciales"; }); function activatab(cual){ $('#js-turismos-btn').addclass('bg-faded'); $('#js-turismos').hide(); $('#js-comerciales-btn').addclass('bg-faded'); $('#js-comerciales').hide(); $('#js-'+ cual + '-btn').removeclass('bg-faded'); $('#js-'+ cual).fadein(300); $('#js-sid').val(cual + "sid"); } });
rather set input's value either of variables turismossid or comercialessid, function sets value string turismossid or comercialessid. doing wrong?
unfortunately can't reference variables through string concatenation*.
to require put turismossid
, comercialessid
values in object, can reference keys of object using string concatenate together. try this:
var sids = { turismossid: "1c0f8e3ec28b09f9487140930a0c0b73", comercialessid: "b31150acd348f775785b7c4a7398a3c6" } if (hash === "#turismos") { activatab("turismos"); $('#js-sid').val(sids.turismossid); } else { activatab("comerciales"); $('#js-sid').val(sids.comercialessid); } // in activatab() $('#js-sid').val(sids[cual + "sid"]);
*you use eval()
it's considered worst thing can possibly use in js code, i'm including in note sake of completeness.
Comments
Post a Comment