Marius Cotofana
Marius Cotofana

Reputation: 1179

Calling a javascript function multiple times

I have a couple of those:

        <div class="enunt">text here</div>
        <div class="ans"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div>
        <div id="slider1" class="slide"></div>

The others have the same structure, but the ids differ by their index number. And I need a function to set up the JQuery sliders. What I did is this:

            function slider(i) {
                $( '#slider' + i ).slider({
                    value:4,
                    min: 1,
                    max: 7,
                    step: 1,
                    slide: function( event, ui, i ) {
                        $( '#amount' + i ).val( ui.value );
                    }
                });
                $( '#amount' + i ).val( $( '#slider' + i ).slider( "value" ) );
            }

And call it like so:

for (var i=1; i<6; i++)
    slider(i);

This does not work at all. Where is my mistake ? It's my first JQuery app, so please be nice.

Upvotes: 4

Views: 3206

Answers (4)

jjenzz
jjenzz

Reputation: 1559

You seem to be overcomplicating things slightly there... something like this is probably all you need (I have added loads of comments to the code to try explain what is going on):

var amountFields = [],
    selector = '.slide',
    opts = {
      value: 4,
      min: 1,
      max: 7,
      step: 1,
      slide: function(e, ui) {
        var i = ui.handle.closest(selector).data('sliderId');
        amountFields[i].val(ui.value);
      }
    };

// because you have used a '.slide' class 
// name on your sliders, you can use .each() 
// to iterate through them instead of using
// your for loop that assumes there are only 
// ever 5 sliders
$(selector).each(function() {
  // get 'i' from the sliders id attribute
  var i = this.id.replace(/[a-z\-_]/gi, '');

  // initialise slider on the element 
  // and store 'i' within the elements
  // data for easy access in the
  // slide method later
  $(this).slider(opts).data('sliderId', i);

  // DOM querying is a hit on performance 
  // so cache the jQuery object for re-use 
  // in the slide method instead of 
  // re-querying the DOM
  amountFields[i] = amountFields[i] || $('#amount' + i);

  // set the amounts initial value using 
  // the opts object instead
  amountFields[i].val(opts.value);
});

Haven't tested this so not 100% there are no errors in the above but something like that should work.

=================================== UPDATE ======================================

Since you thought the above looked more complicated, here is the exact same code without the comments and caching to show you just how simple it actually is:

var opts = {
  value: 4,
  min: 1,
  max: 7,
  step: 1,
  slide: function(e, ui) {
    var i = ui.handle.closest('.slide').data('sliderId');
    $('#amount' + i).val(ui.value);
  }
};

$('.slide').each(function() {
  var i = this.id.replace(/[a-z\-_]/gi, '');
  $(this).slider(opts).data('sliderId', i);
  $('#amount' + i).val(opts.value);
});

I added in the caching before for performance so without it, it will perform slower but will still work. The .replace() bit is getting the slider ID and removing any letters, hyphens or underscores to leave just the number, the bit we need.

Upvotes: 2

Travis J
Travis J

Reputation: 82357

Pass i into your slide function like this:

slide: function( event, ui, i ) {
         $( '#amount' + i ).val( ui.value );
       }

Upvotes: 1

Musa
Musa

Reputation: 97727

The function you assign to slide only takes two parameters, it should be

        function slider(i) {
            $( '#slider' + i ).slider({
                value:4,
                min: 1,
                max: 7,
                step: 1,
                slide: function( event, ui ) {
                    $( '#amount' + i ).val( ui.value );
                }
            });
            $( '#amount' + i ).val( $( '#slider' + i ).slider( "value" ) );
        }

Also make sure you include jquery ui JS and CSS files

http://jsfiddle.net/mowglisanu/Z2aaE/1/

Upvotes: 2

strider
strider

Reputation: 5974

Looks like you are missing a closing brace } in your function slide(i). Otherwise your script worked like a charm for me.

In the future, you should post the error that you got, or that you didn't get an area. You can check your code for errors from within the console of any modern web browser.

Upvotes: 1

Related Questions