Amin Baig
Amin Baig

Reputation: 431

only first value is changed when iterating through express-handlebars each

I am using express-handlebars in my node application. In one of my forms I am storing data in the format 2018-12-01 (YYYY MM DD) as a string. I am also storing time as string in 24 hour format 13:45:00

I have defined a script to use moment for changing the date format:

<script type="text/javascript">
    (function () {
        var NowMoment = $('#displayMoment').val();
        var Date = moment(NowMoment);
        var eDisplayMoment = document.getElementById('output');
        // display output in the preferred format
        eDisplayMoment.innerHTML = Date.format('MMM Do YYYY');
    })();
</script>

in my .handlebars template I am displaying the data received using the following code:

{{#each tasks}}
    <input id="displayMoment" value="{{taskDate}}" hidden>
    <p>{{taskName}} {{taskDate}} {{taskTime}} {{taskStatus}} <span id="output"></span>


        <a class="btn u-btn-primary g-rounded-50 g-py-5" href="/starttask/{{id}}">
            <i class="fa fa-edit g-mr-5"></i> start task
        </a>
    </p>
    {{/each}}

as you can see I have a hidden input which is assigned the {{taskDate}}, I fetch its value in the script and format it to display in the span tag.

The Problem is: Only the first task is formatting the date and showing it, the second or consecutive tasks do not show the formatted date.

Upvotes: 1

Views: 131

Answers (1)

Nathan
Nathan

Reputation: 8149

The id cannot be the same. The HTML specification requires it to be unique. So can lets remove the id attribute from your span and input elements and instead give them an appropriate class attribute definition instead:

<span class="output"></span>

<input class="displayMoment" value="{{taskDate}}" hidden>

Then lets use getElementsByClassName(...) instead of document.getElementById(...) since according to the documentation, getElementById() returns a single element object representing the element whose id property matches the specified string. Assuming a 1 to 1 relationship between input values and the spans we are trying to change the value for we can do something along the lines of this:

 <script type="text/javascript">
        (function () {
            var inputEles = document.getElementsByClassName("displayMoment");
            var spanEles = document.getElementsByClassName("output");
            for(var i=0; i<spanEles.length; i++) {
              var Date = moment(inputEles[i].value);
              spanEles[i].innerHTML = Date.format('MMM Do YYYY');
            }
        })();
    </script>

Hopefully that helps!

Upvotes: 1

Related Questions