I'm a litte confused about native javascript defaultValue functionality. I have understood that the value of the html input must be set and that value is the initial default value.
I wanted to restore a specific input (text) element to its default value when I have this inside a click-event. (Cancel button)
//Restore values
var name_person = $(this).find('.nameOfPerson');
//Attempt 1
name_person.val(name_person.defaultValue);
alert('restored value=' + name_person.val()); //This alerts nothing
//Attempt 2
name_person.val(name_person.prop('defaultValue')); //This alerts the default value
alert('restored value=' + name_person.val());
Why doesn't native defaultValue attribute work when the prop('defaultValue') does? Shouldn't those essentially be the same? The initial value is set with value="bla bla bla" in the input element.
I got it to work (with jQuery), but I just wonder - am I missing something?
It does not work because name_person
is a jQuery object and jQuery does not have a defaultValue
. You need to reference the DOM object
name_person[0].defaultValue
or
name_person.get(0).defaultValue
Default Value in jquery using attr not prop
just try to know some thing ..sample html
<input type="text" name="usrname" value="default"><br>
<input type="submit" value="Submit">
JS
$("input[type=submit]").click(function(){
$("input[type=text]").val(1);
alert($("input[type=text]").prop("value")); // it will return 1
alert($("input[type=text]").attr("value")); // it will return default value
alert($("input[type=text]")[0].defaultValue); // @epascarello posted return default value
});
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.