How to target all input text and password value?

2019-03-01 15:29发布

问题:

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!

回答1:

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/



回答2:

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());
});