问题
I have a very strange problem with Fancybox.
I can't seem to get the .val() of the inputs which are displayed in Fancybox. They have a value of "". The inputs outside of Fancybox, however work.
My code:
<script type="text/javascript">
$(document).ready(function() {
$('a#inline').fancybox({
'hideOnContentClick': false,
'frameWidth': 500,
'frameHeight': $('#avatars').height(),
'callbackOnShow':
function() {
$('#gallery div img').click(function(){
$('#inline img').attr('src', $(this).attr('class'));
$('input#avatar').attr('value', $(this).attr('class'));
});
$('button').click(function(){
console.log($('input#search_avatar'));
return false;
});
}
});
});
And the HTML:
<fieldset>
<div id="avatars" style="float:left; width:500px; display:none;">
<form method="post" action="">
<fieldset>
<input type="text" name="search_avatar" id="search_avatar" />
<button id="search_avatar_submit">Filter</button>
</fieldset>
<div id="gallery">
<div><img src="2_s.jpg" class="2_s.jpg" /></div>
</div>
</form>
</div>
<a id="inline" href="#avatars"><img id="avatar" src="file.png" /></a>
<input type="hidden" name="avatar" value="" id="avatar" />
</fieldset>
So basically. I click on the link. The Fancybox shows up. I add text in the input (this is text), When I click the i will get this (in Firebug):
[input#search_avatar, input#search_avatar This is text]
When i execute this:
$('#search_avatar').val()
I get:
""
Thanks!
回答1:
Fancybox creates a copy of all elements you're going to display and places them into a separate layer. In result, there are two input elements, the original one, and the one you're changing in a Fancybox window.
Here is the image with a visual explanation.
So when you're trying to access "search_avatar" input value using this code:
$('#search_avatar').val()
jQuery returns an empty string because:
- It selects all elements with id=search_avatar (there are two elements in the tree. actually this is a bad idea to have two elements with the same id, so you may think of using classes instead of ids.);
- It returns a value of the first input within selector criteria (which is your first input element with empty value).
To get a value of input element that is located in a Fancybox window you can simply extend jQuery expression:
$('div#fancy_div input#search_avatar')
So, instead of this:
$('button').click(function(){
console.log($('input#search_avatar'));
return false;
});
You may try the following code:
$('button#search_avatar_submit').click(function() {
var searchAvatar = $('div#fancy_div input#search_avatar');
console.log(searchAvatar, searchAvatar.val());
return false;
});
Hope this makes sense and will help you.
回答2:
This works like a charm, using jQuery live events: http://docs.jquery.com/Events/live
$("#fancy_div #yourbuttonId").live("click", function(){
console.log($("#fancy_div #fieldId").val());
return(false);
});
来源:https://stackoverflow.com/questions/1482873/input-inside-fancybox