Search code examples
jqueryappendchatelementmessage

jquery make action forr element append


I am doing a chat, I want to confirm each message send or not?

I do not know how to define the class confirm append, I want to make each class confirm to its answer

 $('#btn').click(function){
var message = $('textarea').val();

$('#chat').append(message+"<span class="confirm">Sending...</span>");

$.post('chat.php', function(result){

if($.trim(result)==='ok'){

this class confirm html('sent');

}else{
this class confirm html('error');
}

}

}

Solution

    • Correct your syntax errors
    • Create a new element (like a DIV for example) by using $("<div/>", {}); and store it into a variable
    • After you get your PHP response use jQuery's .addClass() method to add the desired class to your memorized element

    $('#btn').click(function() {
    
      var message = $('textarea').val();
    
      // Create a new message element
      var $element = $("<div/>", {
        html: message + "<span class='confirm'>Sending...</span>",
        appendTo: "#chat"
      });
    
      // Check response and add class
      $.post('chat.php', {data: message}, function(result) {
        $element.addClass( $.trim(result) === 'ok' ? 'sent' : 'error')
      });
    
    });