How to target all input text and password value?

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!

Answers:

Answer

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/

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.