Search code examples
javascriptjqueryhtmlkeystroke

Reset INPUT without FORM


I have INPUT element and I want to reset the previous value (not necessary original value). There are 2 ways:

  1. Save the value in another variable and pull it out again
  2. Press ESC key. But I don't want users to press ESC but click a button.

So for #2, how can I create a ESC keystroke using jquery?


Solution

  • Here's an SSCCE:

    <!doctype html>
    <html lang="en">
        <head>
            <title>SO question 2079185</title>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    $(':input.remember').each(function() {
                        $(this).attr('data-remember', $(this).val());
                    });
                    $('button.reset').click(function() {
                        $(':input.remember').each(function() {
                            $(this).val($(this).attr('data-remember'));
                        });
                    });
                });
            </script>
        </head>
        <body>
            <input type="text" class="remember" value="foo">
            <button class="reset">Reset</button>
        </body>
    </html>
    

    This basically stores the original value of every input element with a class of remember during onload and instructs the button with a class of reset to restore it whenever clicked.