user2350696
user2350696

Reputation: 5

I need it to return 0 if blank with jQuery datepicker

I have an HTML form which passes the date and time to JavaScript to have some things done to it. The jQuery used to pass the variable to JavaScript is:

var pieces;
  $(document).ready(function() {
      $('#datepicker').datepicker({
          onSelect: function(dateText, inst) {
            window.pieces = dateText.split('/');
            $('#day').val(pieces[0]);
            $('#month').val(pieces[1]);
            $('#year').val(pieces[2]);  

        }
    })
});

The JavaScript used to analyze this uses:

var day1 = parseInt(pieces[1],10);

How can I parse this so that a blank value for datepicker returns anything but an error telling me it doesn't exist?

Upvotes: 0

Views: 108

Answers (3)

RobG
RobG

Reputation: 147383

Presumably the initial string is something like 15/05/2013.

The JS used to analyze this uses:

var day1 = parseInt(pieces[1],10);

How can I parse this so that a blank value for datepicker returns anything but an error telling me it doesn't exist?

I'm not sure what you're asking. If you mean "if the original string is blank, I want a value for day1 of 0", then you can check for a value and either return the value as a Number or 0 depending on the result of the test:

var day1 = typeof pieces[1] == 'undefined' ? +pieces[1] : 0;   

Incidentally, from your code, day1 should be peices[0].

Upvotes: 1

DougM
DougM

Reputation: 2888

You need to add a test inside of onSelect to handle a blank date.

onSelect: function(dateText, inst) {
  if(dateText) {  // newline
    window.pieces = dateText.split('/');
    $('#day').val(pieces[0]);
    $('#month').val(pieces[1]);
    $('#year').val(pieces[2]);  
  }
}

Upvotes: 0

Philipp
Philipp

Reputation: 1445

An easy solution is to check the length of the returned array (from split):

if(window.pieces.length == 3) //an empty string in split does always return 1 element 
{
    alert('date is valid');
}

a much better way is to use regular expressions and check the returned value:

if(dateText.test(/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/))
{
    alert('date is valid');
}

the regex is just copied from http://www.regular-expressions.info/dates.html and does not exactly meet your requirements.

The code is not tested...

Upvotes: 1

Related Questions