How to target all input text and password value?

2019-03-01 15:12发布

I'm trying to figure out how to target every input(text and password) field on all forms on the page document to remove the default value when on focus with this single script:

$(document).ready(function()
{
    Input = $('input');
    default_value = Input.val();

    $('input').focus(function() 
    {
        if($(this).val() == default_value)
        {
            $(this).val("");
        }
    }).blur(function()
    {
        if($(this).val().length == 0)
        {
            $(this).val(default_value);
        }
    });
});

It works only on the first input text element in the first form on my page, but nothing on the rest. Please help!

2条回答
我想做一个坏孩纸
2楼-- · 2019-03-01 15:31

Get all the input type text value:

$("input:text").each(function() {
  alert($(this).val());
});

Get all input type password value:

$("input:password").each(function() {
  alert($(this).val());
});
查看更多
Emotional °昔
3楼-- · 2019-03-01 15:33

That's because val only returns the value of the first selected element, instead of storing the values, you can use defaultValue property of the HTMLInputElement object.

$('input[type=text], input[type=password]').focus(function() {
   if (this.value === this.defaultValue) $(this).val("");
}).blur(function(){
   if (this.value.length === 0) this.value = this.defaultValue;
});

http://jsfiddle.net/MscgZ/

查看更多
登录 后发表回答