Daniel Kellaway
Daniel Kellaway

Reputation: 189

Onload clear all text fields jquery js

How do I clear all text fields on a page, deselect buttons etc? I simply want to refresh the page when it loads.. like holding Shift + Refresh?

Upvotes: 2

Views: 7809

Answers (3)

Bojangles
Bojangles

Reputation: 101473

Give this a try:

$(document).ready(function() {
    $('input[type!="button"][type!="submit"], select, textarea')
         .val('')
         .blur();
});

Clearing the values on buttons and submit buttons will give them a blank label, hence the more complex selector.

Upvotes: 6

nbrooks
nbrooks

Reputation: 18233

I'm not sure if there is a more elegant solution than this, but to simply clear the values you can do this:

$('input[type="text"], textarea').val('');
$('select').each(function() {
    $(this).val($(this).find('option').val());
};

Upvotes: 2

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

If all elements are in form,

then use document.getElementById('your-form-id').reset();

or $('#your-form-id')[0].reset();

Otherwise:

$('input, textarea').each(function() {
    this.value = '';
});

Upvotes: 4

Related Questions