简体   繁体   中英

JQuery - How do I get the value that was set in an input field's value attribute?

I have a an input field <input value="hello"/> . How do I get what is in the value attribute in a cross-browser way? If I do $input.attr('value') or $input.val() , it returns the current value that the user has typed into the field, rather than the value that is set in the value attribute.

If I do input.getAttribute('value') , it returns what I want, but is that cross-browser compatible?

Use the defaultValue property:

input.defaultValue;

$("whatever").get(0).defaultValue;

Using jquery, you would use:

$('input').attr('value');

But the getAttribute() function should be cross browser compatible.

Check out my demo: http://jsfiddle.net/YUGQz/3/ .

It seems that the value attribute is updated when you change the text of the textbox (at least when using jQuery), so .attr('value') doesn't work properly.

But if you try this demo: http://jsfiddle.net/YUGQz/4/ , you can see that using pure JavaScript, you can get the original attribute's value:

document.getElementById('foo').getAttribute('value');

If anyone wants to try this for cross-browser compatibility, that would be nice. Just change the value of the textbox and press the button.

Not enough points to add a comment to Blender

That works under Firefox, Chrome and Safari but don't work under IE (8). In IE you get the same behavior you have with jQuery. It returns the current value of the text box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM