How to reset <INPUT> and <TEXTAREA> values with jquery click() if these elements are not part of any <FORM>?
-
Would be great if you can share some code.Milind Anantwar– Milind Anantwar2013-12-13 12:16:17 +00:00Commented Dec 13, 2013 at 12:16
-
2you can just use the id of the elements to reset it. I think for input it will be $(#id).val('') for textarea $(#id).html('')A Paul– A Paul2013-12-13 12:17:24 +00:00Commented Dec 13, 2013 at 12:17
-
possible duplicate of Clear text areaMilind Anantwar– Milind Anantwar2013-12-13 12:27:10 +00:00Commented Dec 13, 2013 at 12:27
6 Answers
You can reset the values using defaultValue property, both HTMLTextAreaElement and HTMLInputElement support the property, the default value is the value as originally specified in HTML that created these objects.
$('#reset').on('click', function() {
$('input, textarea').val(function() {
return this.defaultValue;
});
});
In case that you only want to reset the values of inputs and textareas that don't belong to a form element you can use .filter() method:
$('#reset').on('click', function() {
$('input, textarea').filter(function() {
return !this.form;
}).val(function() {
return this.defaultValue;
});
});
If the form property is null the input/textarea is not descendant of a form element.
This works:
var elements = $('input,textarea');
$('button').click(function () {
elements.each(function () {
if (!this.form) this.value = this.defaultValue;
});
})
Fiddle
Comments
This solution stores the initial values in the data-oldvalue attribute of the element. When you click the restore button it sets the values back to the initial ones.
Some pointed out you should use .html() to set the value of the textarea. I tried this but it did not set the value while .val() did
$("input").each(function() {
$(this).attr("data-oldvalue", $(this).val());
});
$("textarea").each(function() {
$(this).attr("data-oldvalue", $(this).html());
});
$("button").click(function() {
console.log($(this).attr("data-oldvalue"));
$("input").each(function() {
$(this).val($(this).attr("data-oldvalue"));
});
$("textarea").each(function() {
$(this).val($(this).attr("data-oldvalue"));
});
});