Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting NaN on page load on Jquery UI Slider

I have a slider which on page load should produce a value in the handles of the slider and also another value for a label. I can't understand why on page load I get NaN but when I move the sliders, the value appears.

Please take a look so you can see for yourself Fiddle

The code looks ok, although, the values don't appear in the handles either on page load.

$("#slider1").slider({
    max:350,
    min:100,
    step:10,
    value:100,
    animate: 'true',
    slide: function(event, ui) {  
        $("#amount").val(ui.value);
        $(this).find('.ui-slider-handle').html('<div class="sliderControl-label v-labelCurrent">£'+ui.value+'</div>');
                update();
    }    
});

function addDaysToDate(days) {
  var mths = new Array("Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec");

  var d = new Date();
  d.setHours(d.getHours() + (24 * days));

  var currD = d.getDate();
  var currM = d.getMonth();
  var currY = d.getFullYear();

  return mths[currM] + " " + currD + ", " + currY;
}

$("#slider2").slider({
    max:30,
    min:7,
    value:7,
    animate: 'true',    
    slide: function(event, ui) {  

        $("#days").val(ui.value);
            $(this).find('.ui-slider-handle').html('<div class="sliderControl-label v-labelCurrent">'+ui.value+'<span class="unit"> days</span></div>');
        $("#date").text(addDaysToDate(parseInt($("#days").val())));
                update();
    },
    create: function(event, ui) {
      $("#date").text(addDaysToDate(parseInt($("#days").val())));
    }    
});

$("#days").val($("#slider2").slider("value"));

$("#days").change(function(event) {
  var data = $("#days").val();
  if (data.length > 0)
  {
     if (parseInt(data) >= 7 && parseInt(data) <= 31)
     {
         $("#slider2").slider("option", "value", data);
     }
     else
     {
        if (parseInt(data) < 1)
        {
            $("#days").val("7");
            $("#slider2").slider("option", "value", "7");
        }
        if (parseInt(data) > 31)
        {
            $("#days").val("31");
            $("#slider2").slider("option", "value", "31");
        }
     }
  }
  else
  {
    $("#slider2").slider("option", "value", "7");
  }
  $("#date").text(addDaysToDate(parseInt($("#days").val())));
});

update();
like image 464
Jonah Avatar asked Dec 21 '22 14:12

Jonah


2 Answers

Initially after;

$amount1 = $("#amount").val();

$amount1 is an empty string.

When you then parseInt($amount1) you get NaN not 0 which then makes the whole expression NaN.

Detect and deal with empty values, E.g. $amount1 = parseInt($amount1, 10) || 0;

like image 102
Alex K. Avatar answered Dec 26 '22 21:12

Alex K.


You have to set $('#amount').val(); to default value before calling update()

like image 37
A. Wolff Avatar answered Dec 26 '22 22:12

A. Wolff