Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the textbox value after 5 sec using JQuery?

I have tried this :

  <script type="text/javascript">
        $(function() {
            $("#button").click( function()
            {
                alert('button clicked'); // this is calling
                setTimeout(function(){
                    alert('setTimeout');  // this is not calling
                    document.getElementById('clearTxt').value = "";
                }, 9000);
            }
        );
        });
    </script>

my HTML code:

    <form>
            <input type="text" id="clearTxt"/>                                              
            <input type="submit"  value="Search" id="button"  />
    </form>

But this code is not working.Please help me to solve this issue.

like image 611
Jeetu Verma Avatar asked Jan 31 '26 18:01

Jeetu Verma


1 Answers

When I pasted your code into a fiddle, the alert did fire. However the timeout function won't execute because due to the form tags surrounding the inputs, when you click the submit button you navigate away from the page and the timeout doesn't have time to execute. You should either change the submit to a button, or call preventDefault() in the function to stop the form from submitting.

This code works:

HTML:

<form>
    <input type="text" id="clearTxt" />                                           
    <input type="button" value="Search" id="button" />​
</form>

Script:

$(function() {
    $("#button").click( function () {
        alert('button clicked');
        setTimeout(function(){
            alert('setTimeout');
            document.getElementById('clearTxt').value = "";
        }, 5000);
    });
});

See http://jsfiddle.net/acfkU/1/

like image 90
Levi Botelho Avatar answered Feb 02 '26 09:02

Levi Botelho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!