Passing div value to jQuery function inside Fancybox 2

I am loading this content from test.php

into Fancybox:

<form class="msgarea" action="" method="post">
            <textarea id="usermsg" cols="35" rows="4"></textarea>
            <input type="submit" id="submitmsg" value="Send" />
</form> 

$("#submitmsg").click(function(){
    var clientmsg = $("#usermsg").val();
    alert(clientmsg);
});

      

clientmsg

val doesn't warn anything and any other jQuery function works fine. When I just call test.php

directly and not inside fancybox then it works fine. What could be the problem?

This is how I call Fancybox, if it matters:

EDIT:

index.php where I call test.php looks like this:

<img src="profileimage.jpg" class="fancybox fancybox.ajax" href="test.php?user=123">

$(document).ready(function() {
        $(".fancybox").fancybox({
                        'type':'ajax',
                        "autoScale": false
                    });
    });

      

So when anyone clicks on a profile, the profile is displayed from test.php in fancybox and I want the user to be able to post from msgarea

EDIT 2:

Now inside index.php I changed it to:

$(document).ready(function() {
    $(".fancybox").fancybox({
        'type':'ajax',
        "autoScale": false
    });
    $('.msgarea').on('click', '#submitmsg', function(e){
        e.preventDefault();
        var clientmsg = $("#usermsg").val();
        alert(clientmsg);
    });
});

      

But it doesn't work: /

+3


source to share


1 answer


It does not alert as id #submitmsg does not exist as it is loaded asynchronously.

You need to use event delegation:

$(document).on('click', '#submitmsg', function(e){
  e.preventDefault();
  var clientmsg = $("#usermsg").val();
  alert(clientmsg);
});

      



Document

is just a working example. Instead, you have to use the parent to do this faster.

if it doesn't work debug it by putting console.logs in front of your fancybox, after ur fancybox and inside your click event. if it calls inside the click event the code works and the problem is your markup. make sure there is no double id as they are unique.

+2


source







All Articles