Search code examples
javascriptjqueryduplication

jQuery function duplication. How can I make this shorter?


You can check page here: http://jsfiddle.net/7JhjN/

Basicly, there is a hell of duplication going on and I don't like this. I am sure there is something wrong since it's not a correct programming logic.

How can I shorten this function?

The system works like this: 1. There are 6x select boxes. (option values are the same) 2. There are 6x divs for output. 3. Whenever a select box value gets changed, image in target div gets changed.


Solution

  • how about this:

    HTML:

    <select class='item_early' name="item_early1" data-id="1"><option value="0"></option></select>
    <select class='item_early' name="item_early2" data-id="2"> <option value="0"></option></select>
    <select class='item_early' name="item_early3" data-id="3"> <option value="0"></option></select>
    <select class='item_early' name="item_early4" data-id="4"> <option value="0"></option></select>
    
    <div id="result_item_early1"></div>
    <div id="result_item_early2"></div>
    <div id="result_item_early3"></div>
    <div id="result_item_early4"></div>
    

    Javascript:

    $('.item_early').change( function() {
      var value = $(this).val();
      var id = $(this).data('id');
    
      $('#result_item_early'+id).html('<img src="http://www.sobafire.com/themes/default/images/loading.gif">');
      $('#result_item_early'+id).load('http://www.sobafire.com/ajax.php?ajaxType=ITEM&itemID=' + value);
    });