Formatting problem when injecting date into datetime attribute

Asked

Viewed 42 times

3

I need to assign the current date in a field datetime one-paragraph, for that I 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>");

... 

When inspecting in the browser the entered information is incorrectly formatted:

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

What I need to correct for the result to be like this?:

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

    I don’t understand why that question got -1

3 answers

5


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

$(".container").append(
    $('<p>').attr({
        id: 'msg'+id,
        datetime: date
        }).addClass('message').text(userMessage)
)
  • very good solution. + 1 by organization!

2

You are not opening and closing the quotes correctly for id and datetime, as they conflict with the append statement. Replace the quotation marks (") by apostrophes ('), or add a bar (\) every quote that will circle a string in the program.

$(".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>");

0

Concatenating strings always ends up at some point generating some confusion. That’s why, when this task becomes constant, I usually add a method to the object String of javascript, to facilitate such work.

Behold:

(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 then 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 involved by keys represents the value of the argument, starting with 0, in the method format.

See this example on JSFIDDLE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.