jimi
jimi

Reputation: 213

Reset button to default value for input box

I have an inputbox where visitors can change the value

<input id="custom_coverage" type="text" value="320" name="custom_coverage">

When they change the value, it makes a calculation on the by another jQuery-script.

How can i add a button or a link next to the input box, so visitors can put it back to the default value?

Upvotes: 3

Views: 14679

Answers (6)

Sushanth --
Sushanth --

Reputation: 55750

You can store that value on the data attribute of the button and assign it back to the input on the click of the button.

var $input = $('#custom_coverage'),
    $reset = $('#reset')
$('#reset').data('default', $input.val() );

$reset.on('click', function() {
   $input.val($(this).data('default')); 
});

Check Fiddle

Upvotes: 0

Marcelo Pascual
Marcelo Pascual

Reputation: 820

Yes, you can:

<script type="text/javascript">

$(document).ready(function(){
    var default_value = $('#custom_coverage').val();
    $('#reset_value').click(function(){
        $(this).val(default_value);
        return false;
    });
});

</script>
<input id="custom_coverage" type="text" value="320" name="custom_coverage" id="custom_coverage">
<a href="#" id="reset_value">Reset input</a>

Upvotes: 0

David Ziemann
David Ziemann

Reputation: 970

You can use a simple function to reset the value to whatever you want.

defaultValue = 320;
resetValue = function() {
   $('#custom_coverage').val(defaultValue)
}

Here is the jsFiddle

Upvotes: 0

Richard
Richard

Reputation: 4415

Store the original value in a data attribute, e.g. <input id="custom_coverage" type="text" value="320" data-original-value="320" name="custom_coverage">

And add a button that switches the values again:

<a href="#" class="restore">Restore</a>

<script>

  $(document).on("click", ".restore", function(){
    var custom_coverage = $("input#custom_coverage");
    custom_coverage.val(custom_coverage.data("original-value"));

  });

</script>

Example: http://jsfiddle.net/deDdy/

Upvotes: 10

Bad Wolf
Bad Wolf

Reputation: 8349

If your input is inside of a form you can use a "reset" type input button.

<form action="mySubmit">
<input id="custom_coverage" type="text" value="320" name="custom_coverage">
<input type="reset" value="BUTTON NAME HERE">
</form>

Alternatively if you know what the original value is you can do something like this

<input type="button" onclick="$('#custom_coverage').val('ORIGINAL VALUE');" value="Reset"/>

Upvotes: 0

Alejandro Iv&#225;n
Alejandro Iv&#225;n

Reputation: 4061

You'd do it this way:

<input type="reset" value="Restore" />

But it will reset all the form, not only one input.

Upvotes: 2

Related Questions