开发者

Streamlining my javascript with a function

i have a series of select lists, that i am using to populate text boxes with ids. so you click a select option and another text box is filled with its id.

with just one select/id pair this works fine, but i hav开发者_开发知识库e multiples, and the only thing that changes is the id of the select and input.. in fact just the ending changes, the inputs all start with featredproductid and the select ids all start with recipesproduct and then both end with the category.

i know that listing this over and over for each category is not the way to do it. i think i need to make an array of the categories var cats = ['olive oil', "grains", "pasta"] and then use a forEach function? maybe?

here is the clunky code

window.addEvent('domready', function() {
    $('recipesproductoliveoil').addEvent('change', function(e){
       pidselected = this.options[this.selectedIndex].getProperty('value') ;
   $("featuredproductidoliveoil").setProperties({
       value: pidselected}); ;
    });
       $('recipesproductgrains').addEvent('change', function(e){
           pidselected = this.options[this.selectedIndex].getProperty('value') ;
       $("featuredproductidgrains").setProperties({
           value: pidselected}); ;
        });
      $('recipesproductpasta').addEvent('change', function(e){
          pidselected = this.options[this.selectedIndex].getProperty('value') ;
      $("featuredproductidpasta").setProperties({
          value: pidselected}); ;
       });
    $('recipesproductpantry').addEvent('change', function(e){
        pidselected = this.options[this.selectedIndex].getProperty('value') ;
    $("featuredproductidpantry").setProperties({
        value: pidselected}); ;
     });

});

keep in mind this is mootools 1.1 (no i cant update it sorry). i am sure this is kind of basic, something i seem to have wrapping my brain around. but i am quite sure doing it as above is not really good...


You're close. This is how you could do it:

var cats = ['oliveoil', 'grains', 'pasta'];
for (i in cats) {
    addChangeFunction(cats[i]);
}

function addChangeFunction(name) {
    $('recipesproduct' + name).addEvent('change', function(e) {
        pidselected = this.options[this.selectedIndex].getProperty('value');
        $('featuredproductid' + name).setProperties({
            value: pidselected
        });
    });
}


Something like this might help:

 function bindSelectFeature(select, featured) {
    $(select).addEvent('change', function(e){
        pidselected = this.options[this.selectedIndex].getProperty('value') ;
        $(featured).setProperties({
          value: pidselected
        });
     });
  });
  bindSelectFeature('recipesproductpasta','featuredproductidpasta');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜