Koen Certyn
Koen Certyn

Reputation: 193

Elm - Update date input field from js does not work

I'm working on a project with elm, but currently I'm stuck on the following problem: I want to update a generated input field from elm

newDate address =
    header
      [ id "header" ]
      [ input
          [ id "datePicker"
          , autofocus False
          , type' "date"
          , onEnter address Add
          ]
          []
      ]

My initial thought was to integrate my .elm code with html, which I succeeded doing so, to enable me to create custom js scripts to interact with the dom.

However, when adding the following script (to put the date to the current day) it does not seem to update the date field.

    $(document).ready( function() {
        var now = new Date();

        var day = ("0" + now.getDate()).slice(-2);
        var month = ("0" + (now.getMonth() + 1)).slice(-2);

        var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

        $('#datePicker').val(today);
    });

But, if I execute this code in the browser console itself, it does work.

Any thoughts?

Thanks in advance!

-K

added : on request the elm integration into html

<html>

  <head>
    <title>Embedded Elm</title>
    <script type="text/javascript" src="elm.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  </head>

    <body>
        <div id="main" style="width:50%; height:400px;"></div>
    </body>

    <script type="text/javascript">
    var mainDiv = document.getElementById('main');
    Elm.embed(Elm.Main, mainDiv);

    $(document).ready( function() {
        var now = new Date();

        var day = ("0" + now.getDate()).slice(-2);
        var month = ("0" + (now.getMonth() + 1)).slice(-2);

        var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
       $('#datePicker').val(today);
    });


    </script>

</html>

Upvotes: 2

Views: 300

Answers (1)

grumpyjames
grumpyjames

Reputation: 366

I guess that my initial instinct is accurate, i.e the behaviour of Elm.embed is more asynchronous than we would perhaps like, and the ready callback is firing before the element is present within the DOM. It would be worth observing the sequence of events in the debugger to verify this is the case.

Edit: Having just had a quick look myself, it looks like the first elm frame may be rendered synchronously by the call to embed. Are you confident that your application's initial state results in that form component's inclusion?

In any case, if what you want to achieve is to initialise the field once with the current date, this question might be useful: Initialize model with current date

Edit 2: One other thing that could be causing some issues is including the <script> tag after the <body> tag closes. This question seems to suggest that is not a great idea; perhaps you could also try including it before <body> is closed?

Upvotes: 1

Related Questions