How to reset <INPUT>
and <TEXTAREA>
values with jquery click()
if these elements are not part of any <FORM>
?

- 6,072
- 9
- 52
- 78
-
Would be great if you can share some code. – Milind Anantwar Dec 13 '13 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 Dec 13 '13 at 12:17
-
possible duplicate of [Clear text area](http://stackoverflow.com/questions/8284960/clear-text-area) – Milind Anantwar Dec 13 '13 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.

- 143,282
- 16
- 168
- 197
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"));
});
});

- 9,933
- 10
- 55
- 91
-
No, not erase. I had some value before edit, than after click old value must be returned. – zur4ik Dec 13 '13 at 12:19
-
I dont think $("textarea").val(""); will work. But I may be wrong .. you need .html('') here. – A Paul Dec 13 '13 at 12:19
-
The you first need to store all those values beforehand and then restore them I will create an example. – Bas van Dijk Dec 13 '13 at 12:19
-
use some hidden variables.. store the values there and then again restore them. – A Paul Dec 13 '13 at 12:20
Try this:
$('#click').on('click', function() {
$("input[type='text'], textarea").val('');
});

- 3,413
- 2
- 16
- 20
Try This...
$('#btnID').click(function(){
$('#FormID')[0].reset();
});

- 1,287
- 6
- 10