开发者

Why do I get [object Object] in jQuery?

Here's my simple function to hide an input value on click and show it again on blur:

// show input value then hide on click
$('.showHide').click(function() {
 开发者_JS百科   var originalValue = $(this).val();
    $(this).attr("value", '');
});
$('.showHide').blur(function(originalValue) {
    $(this).attr("value", originalValue);
});

But showing the original value again isn't working, instead I get this: [object Object] on blur, why?


It's a scope issue

// show input value then hide on click
var originalValue;
$('.showHide').click(function() {
    originalValue = $(this).val();
    $(this).attr("value", '');
});
$('.showHide').blur(function() {
    $(this).attr("value", originalValue);
});

should work


When blur calls your handler function it is passing an event object, not the original value. Try storing the value like this:

// show input value then hide on click
$('.showHide').click(function() {
    jQuery.data($(this), 'originalValue', $(this).val();
    $(this).attr("value", '');
});
$('.showHide').blur(function() {
    $(this).attr("value", jQuery.data($(this), 'originalValue'));
});


I'm not positive without seeing your html but I think your problem may be the local declaration of originalValue in the first function and trying to use it in the second function. Try this:

// show input value then hide on click
var originalValue = "";
$('.showHide').click(function() {
    originalValue = $(this).val();
    $(this).attr("value", '');
});
$('.showHide').blur(function(originalValue) {
    $(this).attr("value", originalValue);
});


  1. originalValue is within the scope of the function it was declared in, and doesn't exist outside of it. You need to declare it outside of the function first.

  2. The value that gets passed into an event callback is the event object. As such, in the blur callback function, originalValue is set to the event object, which is why it is non-null.

What you want is something like this:

var originalValue;

$('.showHide').click(function() {
    originalValue = $(this).val();
    $(this).attr("value", '');
});
$('.showHide').blur(function() {
    $(this).attr("value", originalValue);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜