Clay
Clay

Reputation: 53

foo.substr gives "Is not a function" error

I'm using Jquery's datepicker plugin (which works fine). Then I need to extract the "day of the week" from the picked date.

When using foo.substring(0,3) to assign the first three characters of the datepicker('getDate') I get: TypeError foo.substr is not a function.

$(function () {
    $("#textDatepicker").datepicker();
});

function selectedDay() {
    var foo = $("#textDatepicker").datepicker('getDate');

    //IF USED.... alert(foo);
    //retuens (for example)..... 
    //"Thu Jul 18 00:00:00 GMT-0400 (Eastern Standard Time)"

    var weekday = foo.substr(0, 3)
    document.getElementById("dayofweek").innerHTML = "The day of the week selected is: " + weekday;
}

<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="https://jquery-blog-js.googlecode.com/files/SetCase.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
</head>
<body>
Select Date:&nbsp;<input type="text" id="textDatepicker" onchange="selectedDay();">
<br><br>
<span id="dayofweek">Selected day of week replaces this</span>
</body>

I have also pasted at: jsfiddle

Any help would be appreciated.. Thanks in advance...

Upvotes: 1

Views: 17141

Answers (5)

Ismael ozil
Ismael ozil

Reputation: 571

called the toString(); method before calling the subString(); like foo.toString().subString(start,length); Worked for me

Upvotes: 0

sunshine
sunshine

Reputation: 166

foo.substr(0,3) is the culprit. It returns a date object and you can do substr on a date object. You could fix the problem by using the code below

function selectedDay() {
    var foo = $("#textDatepicker").datepicker('getDate');

    //IF USED.... alert(foo);
    //retuens (for example)..... 
    //"Thu Jul 18 00:00:00 GMT-0400 (Eastern Standard Time)"

    var weekday = foo.getDay();
    document.getElementById("dayofweek").innerHTML = "The day of the week selected is: " + weekday;
}

Upvotes: 0

adeneo
adeneo

Reputation: 318222

var foo = $("#textDatepicker").datepicker('getDate');

returns a Date object, not a string, and has no method substr()

FIDDLE

You can solve it by removing that unsightly inline event handler and doing :

$("#textDatepicker").datepicker({
    onSelect: function() {
        var date = $(this).datepicker('getDate');
        var day  = $.datepicker.formatDate('DD', date);
        $('#dayofweek').html(day);
    }
});

FIDDLE

Upvotes: 6

The Alpha
The Alpha

Reputation: 146201

Use

var weekday = foo.toString().substr(0, 3);

DEMO.

Upvotes: 7

Jonast92
Jonast92

Reputation: 4967

$("#textDatepicker").datepicker('getDate');

is an object. You can't take the substring of an object with substr.

Upvotes: 1

Related Questions