- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Text Field Returns “Undefined”
Hey guys,
I’m trying to create an input form that expands on click. Like the Apple search box.
Everything is all good, except when I click inside the input field, the word “undefined” shows up. How can I have it display no text? The user needs to be able to type in there.
This is what I have:
$(document).ready(function() {
var inputwidth = '200px';
var inputwidthReturn = '140px';
$('#search input').focus(function(){
$(this).val(function() {
$(this).val('');
});
$(this).animate({
width: inputwidth
}, 500 )
});
$('#search input').blur(function(){
$(this).val('Search');
$(this).animate({
width: inputwidthReturn
}, 800 )
});
});
Hope someone can help me out. Thanks!
When your using an anonymous function inside a jQuery method such as val() you need to return the value you want otherwise jQuery will interpret the response as undefined.
Also you don’t need to use 2 separate event declarations, the jQuery bind() method allows for multiple binded events using one selector.
$(function() {
var inputwidths = [200, 140];
$('#search input').bind({
focus : function() {
$(this).val(function() {
return '';
});
$(this).animate({
width : inputwidths[0]
}, 500);
},
blur : function() {
$(this).val('Search');
$(this).animate({
width : inputwidths[1]
}, 800);
}
});
});
Amazing, it works perfectly! Thank you so much!
As you can see, I’m not the greatest with jQuery haha. Definitely opens my eyes to a few things now.
No problem, a lot of common issues you can solve by visiting the jQuery docs as they have been updated a lot since the 1.4 release.