I got six jQuery UI sliders in a Wordpress metabox, I get they're values and output the average to a text input field (#pm_overall_score), this is the JS that handles this:
var sum = 0 ;
var nums = 0;
$('.rwmb-slider').bind({
slidechange : function(event,ui) {
sum = 0;
nums = 0;
$('.rwmb-slider').each(function(){
var value = $( this ).slider( "option", "value" );
if(value != 0 )
{
sum += value ;
nums++;
}
});
var avg = sum / nums ;
$('#pm_overall_score').val(Math.floor(avg));
console.log(avg);
}
}).slider();
Works fine except that when I save the values, on page reload the text input displays huge numbers and I can't understand why this is happening nor the math behind it.
Ex:
First Slider > Value 5,
Second Slider > Value 15
Saves the correct average (10) but on the input field shows 257 on page reload. Now if I move the third slider to 10, the number becomes 17170 (??). I need to move back all the sliders to 0 to make it work again. I'm not a jQuery expert though, any idea about why this is happening or any alternative on average calculation?
Thanks
EDIT: I also post the code that handles the sliders if it's helpful:
jQuery( document ).ready( function( $ )
{
var
id = null
, el = null
, input = null
, label = null
, format = null
, value = null
, update = null
;
$( '.rwmb-slider' ).each( function( i, val )
{
id = $( val ).attr( 'id' );
el = $( '#' + id );
input = $( '[name=' + id + ']' );
label = $( '[for=' + id + ']' );
format = $( el ).attr( 'rel' );
$( label ).append( ': <span id="' + id + '-label"></span>' );
update = $( '#' + id + '-label' );
if (
!$( input ).val()
|| 'undefined' === $( input ).val()
|| null === typeof $( input ).val()
)
{
$( input ).val( $( el ).slider( "values", 0 ) );
$( update ).text( "0" );
}
else
{
value = $( input ).val();
$( update ).text( value );
}
if ( 0 < format.length )
$( update ).append( ' ' + format );
el.slider(
{
value: value,
slide: function( event, ui )
{
$( input ).val( ui.value );
$( update ).text( ui.value + ' ' + format );
}
} );
} );
} );