maciekk67
maciekk67

Reputation: 13

Can't call jQuery function

I have a problem with my code. I want to call a function but it's not working.

First, function show() displays button. This button has id='send' and it's inside the div with class='messagebox'. I want to call function on button click. (I call function show in php script)

echo<<<ENDL 

<div class="friendslistimgbox" onclick="show('$id','$login','$photo')">....</div>

ENDL;

$(.messagebox #send) or $(.messagebox > #send) are not working

$(document).ready(function(){
    var conn = new WebSocket('ws://localhost:8080');
    conn.onopen = function(e) {
    console.log("Connection established!");
    };

    conn.onmessage = function(e) {
        console.log(e.data);
        var data = JSON.parse(e.data);
        var row = data.from+": "+data.msg+"<br/>";

        $("#chats").append(row);
    };

    $(".messagebox #send").click(function(){
        var userId = $("#userId").val();
        var msg = $("#msg").val();
        var data = {
            userId: userId,
            msg: msg
        };
        conn.send(JSON.stringify(data));
    })
})

function show(id,login,photo){      
    $('.messagebox').html("<input type='hidden' id='userId' value='"+login+"'><input type='text' id='msg' class='sendmessage'><button id='send' type='submit' class='button_sendmessage'><i class='icon-right-dir'></i></button>");
    $('#message_to').html("<a href='"+login+"'><img src='../userphotos/"+photo+"'>"+login+"</a>");
    $("#allmessagesbox").css("visibility","visible");
}

HTML /

<div class="allmessagesbox" id="allmessagesbox">
    <div class="messages">
        <div class="message_to" id="message_to"></div>
    </div>
    <div class="messagebox"></div>
</div>
<div id="chats"></div>

Upvotes: 1

Views: 716

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

You'll need to use the .on() method to register events with DOM elements that are dynamic (ie like your button, which might exist in the future).

In the case of your code, you can use on() in the following way:

// Replace this line:
// $(".messagebox #send").click(function(){
// With this:
$("body").on("click", ".messagebox #send", function(){

    var userId = $("#userId").val();
    var msg = $("#msg").val();
    var data = {
        userId: userId,
        msg: msg
    };
    conn.send(JSON.stringify(data));
})

This can basically be read and understood as:

// For any dynamic element in scope or child of the body
$("body")
// Register a click event with any element that matches the
// .messagebox #send selector either now, or in the future
.on("click", ".messagebox #send", function(){

...

}));

For more information on on(), see the jQuery documentation

Upvotes: 1

Related Questions