2

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

zur4ik
  • 5,646
  • 8
  • 48
  • 74

6 Answers6

3

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.

http://jsfiddle.net/E2tbk/

undefined
  • 136,817
  • 15
  • 158
  • 186
1

This works:

var elements = $('input,textarea');
$('button').click(function () {
    elements.each(function () {
        if (!this.form) this.value = this.defaultValue;
    });
})

Fiddle

Sergio
  • 27,160
  • 10
  • 79
  • 126
0

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"));    
    });

});

See: http://jsfiddle.net/zvPK7/

Bas van Dijk
  • 7,931
  • 8
  • 51
  • 81
0

use this:

document.getElementById('yourInputID').value = "";
Majid
  • 12,271
  • 14
  • 71
  • 107
0

Try this:

$('#click').on('click', function() {

    $("input[type='text'], textarea").val('');
});
Mr.G
  • 3,023
  • 2
  • 14
  • 19
-1

Try This...

$('#btnID').click(function(){
        $('#FormID')[0].reset();
});
Pradeep Pansari
  • 1,287
  • 6
  • 10