Search code examples
javascripttwitter-bootstrapdom-events

Open link when user changes date in date picker


I am using a Twitter Bootstrap datepicker (http://www.eyecon.ro/bootstrap-datepicker/)

What I am trying to do is use the input value (e.g. 15-02-2012 ) to load a page, when the user changes the date.

The input box uses this code:

    <div class="input-append date"  data-date="12-02-2012" data-date-format="dd- mm-yyyy">
    <input class="span9" size="16" id="dp3" type="text" value="12-02-2012" onchange="myFunction()">
    <span class="add-on"><i class="icon-th"></i></span>

And the JavaScript to reload the page is this:

<script>
function myFunction()
{
datevalue = document.getElementById("dp3").value
window.open(datevalue,"_self");
}
</script>

The problem is when the date is changed in the date picker (input id = dp3), nothing happens, the page does not reload, but when I tried attaching myFunction() to another text box, it does work, and it is able to grab the value in the datepicker (dp3).

So the problem is that JavaScript is not recognising the change in value of the datepicker (id=dp3). Does anyone know why this is the case?


Solution

  • I see you took the code from the example n°3 of your link, but you switched the id to the wrong tag.

                           Here  --.
                                   V
    <div class="input-append date" id="dp3" data-date="12-02-2012" data-date-format="dd-mm-yyyy">
        <input class="span2" size="16" type="text" value="12-02-2012" readonly="">
        <span class="add-on"><i class="icon-calendar"></i></span>
    </div>
    

    If you leave the id on the input tag and keep the original JS code, the .datepicker() method will be called on the wrong element (the input): it is meant to be called on the parent div.

    Then, on your jQuery, you should bind the changeDate event of your date-picker, and not the onChange of the input tag itself.

    You could try something like this (using jQuery) :

    $('#dp3').datepicker().on('changeDate', function() {
        //Retrieve the date located on the data of your datepicker
        var datevalue = $('#dp3').data("date");
    
        //You can take the value from the input as well if you want
        //The input tag doesn't really need an ID to be retrieved (see comments)
        //var datevalue = $('#dp3 input').val();
    
        window.open(datevalue,"_self");
    });
    

    Edit : here is a working fiddle with minor changes.