Jhonathan Jhonathan - 18 days ago 6
Javascript Question

JavaScript - Displaying saved comment the name and comment are displayed next to each other rather than on top?

I want the JS to be able to save the comment of the inputted name and comment and for it to be displayed after clicking the Save Comment button underneath the Comments at the bottom.

It does that but the name and the comment are side by side instead of on top of each other and looks confusing

// utility functions for localstorage
function setObject(key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
}

function getObject(key) {
var storage = window.localStorage,
value = storage.getItem(key);
return value && JSON.parse(value);
}

function clearStorage() {
window.localStorage.clear();
}

// Clear inputfields and localstorage
function clearComment(){
$('#txt1').val('');
$('#namebox').val('');
clearStorage();
}

function saveComment(){
var cText = $('#txt1').val(),
cName = $('#namebox').val(),
cmtList = getObject('cmtlist');

if (cmtList){
cmtList.push({name: cName, text: cText});
setObject('cmtlist', cmtList);
}else{ //Add a comment
setObject('cmtlist', [{name: cName, text: cText}]);
}

bindCmt();
}

function bindCmt(){
var cmtListElement = $('#cmtlist'),
cmtList = getObject('cmtlist');

//Out with the old
cmtListElement.empty();
//And in with the new
$.each(cmtList, function(i, k){
cmtListElement.append( $('<p><span>'+ k.name +'</span>'+ k.text +'</p>') );
});
}

//Get the comments on page ready
$(function(){
bindCmt();
});


it looks like this:

the NameTest and CommentTest are next to each other in the Comments section

Answer

You could add an html break <br> to the line below:

cmtListElement.append( $('<p><span>'+ k.name +'</span><br>'+ k.text +'</p>') );
Comments