开发者

How to save the value of INPUT in variable?

How to save the value of INPUT in variable to not to write a lot of duplicate code?

like var input = $(this).val();

full example

<div id="form">
    1. <input type="text" value="title" />
    2. <input type="text" value="value" />
</div>

$(function(){
  $('#form input:eq(0)').bind({
    focus: function(){
       if($(this).val()=='title'){
            $(this).val('');
        }
     },
     blur: function(){
       if($(this).val() == ''){
          $(this).val('title');
        }
     }
  });

  $('#form input:eq(1开发者_如何学Python)').bind({
    focus: function(){
      if($(this).val()=='value'){
         $(this).val('');
      }
    },
     blur: function(){
        if($(this).val() == ''){
           $(this).val('value');
        }
    }
  });
});


I'm not exactly sure what you are asking, but this refactoring will work for toggling the value. EDIT: added default attribute to the html elements and shortened jQuery (still readable though) http://jsfiddle.net/UmZeZ/

<div id="form">
    1. <input type="text" value="title" default="title" />
    2. <input type="text" value="value" default="value" />
</div>


$(function() {
    $('#form input').bind('focus blur', function() {
        var value = $(this).attr('default');
        if ($(this).attr('value') == value) {
            $(this).attr('value', '');
        } else if ($(this).attr('value') === '') {
            $(this).attr('value', value);
        }
    });
});


To accomplish what you want, I would suggest using the HTML5 placeholder attribute. With Modernizr, we can detect browser support for this feature, and with this simple piece of code, we can get it to work even for browsers that do not support placeholder.

if(!Modernizr.input.placeholder){
    var input = $('input[type="text"]');

    input.focus(function(){
        if(this.value === this.getAttribute('placeHolder')) this.value = '';
    }).blur(function(){
        if(this.value === '') this.value = this.getAttribute('placeHolder');
    }).blur();
}

See a live demo of this here: http://www.jsfiddle.net/yijiang/cTDsL/1


Here is my solution. I would work to any field which has class="set-default"

Checkout the working example

Here is the code:

$(function(){
    $('.set-default').bind({
    focus: function(){
        if(typeof($(this).data('def')) == 'undefined'){
               $(this).data('def', this.value)
        }
        if(this.value == $(this).data('def')){
           this.value = '';
        }
     },
     blur: function(){
       if(this.value == ''){
          this.value = $(this).data('def');
       }
     }
    })
});

basically all fields which had the class set-default will act as you like. You can always change the selector to $('#form input') but I think it's not useful.

HTH

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜