开发者

jquery using data for cross-function variables

Hey all. Basically I have a page full of text input fields with default values in them.

When a user focuses on the input, I want the value to be set to nothing, but then if the user focusses out (on blur) and the input is still empty, I want to change its value back to what it was originall开发者_JAVA技巧y.

At the moment I have this, but it isn't working:

$("#login input").focus(function(){
    $(this).val("");
      $(this).data({
       value: $(this).val()
      });
}); 
$("#login input").focusout(function(){
  if($(this).val()=="") {
   $(this).val($(this).data("value"));
  }
});

What I need is some sort of NOT .change() kind of thing? Maybe?

Thanks in advance


Re-write it a bit (reverse the order in the focus!), like this:

$("#login input").focus(function(){
    $.data(this, "value", $(this).val());
    $(this).val("");
}); 
$("#login input").focusout(function(){
  if($(this).val()=="") {
   $(this).val($.data(this, "value"));
  }
});

The $.data() shortcut is a bit neater and less wasteful (no extra jQuery objects)...but the main problem is you need to swap the order in the focus, you were clearing the value before storing it, so it was being stored as "" every time.


it's not working because first you set an empty value and then you store that empty value. Try this:

$("#login input").focus(function(){
  $(this).data({
    value: $(this).val()
  });
  $(this).val("");
}); 
$("#login input").focusout(function(){
  if($(this).val()=="") {
   $(this).val($(this).data("value"));
  }
});


<div id="login">
<input type="text" data-default="default value"/>
</div>

<script type="text/javascript">
$("#login input).focus(function(){
  var $this = $(this);
  if($this.val() == $this.attr('data-default')) $this.val("");
}).blur(function(){
  var $this = $(this);
  if($this.val() == "") $this.val($this.attr('data-default'));
}).blur();
</script>

This way you can put another than default value in the fields, without getting them removed. i.e. the user enters a false password you could pre fill the username with the one provided by the user in the first attempt. if you do it your way. this value will be removed if i focus on this field.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜