2

$(#email).attr('value') should give the original default value of an input, but with jQuery 1.8.1, gives the current value. Why is this? When was this change made? What steps should I take so I can be aware of these changes and not stumble upon them after finding things don't work as expected. Thank you

http://jsfiddle.net/ufrHD/2/ using jQuery 1.8.1

http://jsfiddle.net/ufrHD/3/ using jQuery 1.9.1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
        <title>Input</title> 
        <script src="http://code.jquery.com/jquery-1.8.1.js" type="text/javascript"></script> 
        <script type="text/javascript">
            $(function() {
                $("#click").click(function() {alert("$('#email').val()="+$('#email').val()+"\n$('#email').attr('value')="+$('#email').attr('value'));});
            });
        </script>
    </head>

    <body>
        <button id="click">Click</button>
        <input type="email" name="name" id="email" value="email@example.com" />
    </body> 
</html>
user1032531
  • 24,767
  • 68
  • 217
  • 387

2 Answers2

3

The change was made in 1.9 as documented in http://jquery.com/upgrade-guide/1.9/#attr-versus-prop- as well as some blog posts. The old pre-1.9 behavior was a bug.

The best way to be aware of the changes is to read the blog posts and api.jquery.com documentation. If you see docs issues that need clarification file an issue or pull request at https://github.com/jquery/api.jquery.com/ .

Dave Methvin
  • 1,458
  • 10
  • 12
2

It isn't obvious that $.attr('value') should return the default value. As a rule of thumb, if something doesn't seem obvious, your mileage might vary.

Therefore you should not be using this to get the default value. Instead, store the default value within the elements for future retrieval:

$(function () {
    $("[value]").each(function () {
        $(this).attr("data-def-value", $(this).val());
    });
);

Then you can get it using:

$(element).attr("data-def-value");

EDIT: As billyonecan pointed out you can access the elements defaultValue

MMM
  • 7,221
  • 2
  • 24
  • 42
  • 2
    Ah, of course. https://developer.mozilla.org/en-US/docs/DOM/HTMLInputElement#Properties – MMM May 07 '13 at 13:59