Formatting problem when injecting date into attribute datetime

3

I need to assign the current date in a datetime field of a paragraph, for that I have implemented:

...

var newDate = new Date(),
date = newDate.getFullYear() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getDate() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();

$(".container").append("<p id=msg" + id + " class='message' datetime=" + date + ">" + userMessage + "</p>");

... 

Inserting the inserted information into the browser is formatted incorrectly:

<p id="msg1" class="message" datetime="2015-2-23" 11:26:48="">teste</p>

What do I need to fix so that the result is like this?:

<p id="msg1" class="message" datetime="2015-2-23 11:26:48">teste</p>
    
asked by anonymous 23.02.2015 / 15:31

3 answers

5

Previous answers will help you. But to avoid confusion and make the code more readable, always try to use append as follows:

$(".container").append(
    $('<p>').attr({
        id: 'msg'+id,
        datetime: date
        }).addClass('message').text(userMessage)
)
    
23.02.2015 / 15:42
2

You are not opening and closing quotation marks correctly for id and datetime because they conflict with the append statement. Replace the quotation marks (% with%) with apostrophes (% with%), or add a slash ( " ) to each quotation mark that surrounds a program string.

$(".container").append('<p id="msg' + id + '" class="message" datetime="' + date + '">"' + userMessage + '"</p>"');

or

$(".container").append("<p id=\"msg" + id + "\" class=\"message\" datetime=\"" + date + "\">" + userMessage + "</p>");
    
23.02.2015 / 15:35
0

Concatenating strings always ends up causing some confusion. This is why, when this task becomes constant, I usually add a method to the object String of javascript , to facilitate this type of work.

See:

(function(String){
   // adicionamos o método format a qualquer string do javascript
    String.prototype.format = function () {

        var args = arguments;

        return this.replace(/\{(\d+)\}/g, function(match, index){

            return args[index];

        }).toString();

    }

})(String);

And later we use it as follows.

var data = "<p id='msg{0}' class='message' datetime='{1}'>{2}</p>".format(id, date, userMessage )
$(".container").append(data);

In this case, the number of keys represents the value of the argument, starting from 0 , in method format .

See this example on JSFIDDLE

    
23.02.2015 / 15:39