Andrew Grimm
Andrew Grimm

Reputation: 81631

How to reset an individual input element with JQuery

How do I reset an individual input element with JQuery (is it JQuery, or JavaScript)?

How to reset a form using jQuery with .reset() method shows how to reset an entire form, but I want to reset individual elements, not the entire form.

Upvotes: 3

Views: 2321

Answers (6)

Mantas Dainys
Mantas Dainys

Reputation: 91

It's very simple

$('#escape').on('click', function(e){
                        $('#field').val($('#field').defaultValue);
});

Upvotes: 1

Michael
Michael

Reputation: 125

Resetting a single input field with jQuery:

$('#myField').val($('#myField').prop("defaultValue"));

Upvotes: 1

Pindo
Pindo

Reputation: 1625

If the value has been set in the input element, then it can be referenced back to

 $('#resetName').click(function () {
     $('#name').val($('#name').attr('value'));
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="TEST" id="name"></input>
    <input value="99" id="age"></input>
    <input value="1 Apr 2000" id="DOB"></input>
    
    <button id="resetName" value="Reset Name">Reset Name</button>

Upvotes: 1

Roumelis George
Roumelis George

Reputation: 6746

You can access the original value of an input element with the defaultValue attribute.

For example you can do this:

var myInput = document.getElementById("myInput");

myInput.value = myInput.defaultValue;

Upvotes: 4

Shaunak D
Shaunak D

Reputation: 20646

You might need to use a hack for this.

Use .wrap() to temporarily wrap the required input with a form.

$('#input1,#input2').val('testUpdated');
$('#input1').wrap('<form/>');
$('#input1').closest('form')[0].reset();
$('#input1').unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input id="input1" value="test"/>
    <input id="input2" value="test"/>
</form>

Upvotes: 2

Brownman Revival
Brownman Revival

Reputation: 3850

FIDDLE

TRY USING $(this).val(defaultVal); as

('#maincontainer').find('textarea,input[type=text]').each(function () {
        var defaultVal = $(this).data('default');
        $(this).val(defaultVal);
    });

Change the ID if you want a specific input to be cleared here i just show how to clear input and textarea in general

Upvotes: -1

Related Questions