Reputation: 99
I load 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);
});
The clientmsg
val alerts nothing, while 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's matter:
EDIT:
The 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 click on the profileimage, the profile is shown from test.php into fancybox and I want the user to be able to send messages from the 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's not working :/
Upvotes: 3
Views: 406
Reputation: 1076
It's not alerting because the id #submitmsg doesnt exist since it's loaded asynchronous.
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 - you should use a parent element instead to make this faster.
if it's not working debug it by putting console.logs before your fancybox, after ur fancybox and inside your click event. if it triggers inside the click event the code works and the problem is your markup. make sure there are no double ID's since they are unique.
Upvotes: 2