Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery trigger function triggers multiple times

Tags:

jquery

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("input").select(function(){
    $("input").after("Text selected ");
  });
  $("button").click(function(){
    $("input").trigger("select");
    //$('input')[0].select();
});
});
</script>
</head>
<body>
<input type="text" name="FirstName" value="Hello World" />
<br/>
<button>Trigger select event</button>
</body>
</html>

The code above triggers select handler 3 times in chrome... That is 3 pieces of 'Text selected' appear.. I don't know why. How to fix this? By the way, if I use the commented way instead, still two pieces would appear. Why?

like image 267
Euclid Ye Avatar asked Dec 15 '25 08:12

Euclid Ye


1 Answers

This is little bit surprising. It occurs not only in Chrome. But also in Safari and Opera too.

Solution 1:

My suggestion for you is return false;. Because in this case select event handler must return false. So that we can stop executing the further select event handlers. But calling .preventDefault() and .stopPropagation() will not accomplish this. Because here there is no parent-child relationship for event bubbling.

Try this code snippets:

$(document).ready(function () {
            $("input").select(function () {
                $("input").after("Text selected ");
                return false;
            });
            $("button").click(function () {
                $("input").trigger("select");
            });
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" name="FirstName" value="Hello World" />
<br />
<button>Trigger select event</button>

Solution 2: (As per your requirement)

Try with .on() and .off() method. It will do the trick.

$(document).ready(function () {
            $("input").on('select', appendWord);

            $("button").click(function () {
                $("input").trigger('select');
                $("input").off('select');
                setTimeout(function () {
                    $("input").on('select', appendWord);
                }, 300);
            });

            function appendWord() {
                $("input").after("Text selected ");
            }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" name="FirstName" value="Hello World" />
<br />
<button>Trigger select event</button>

Hope this helps you.

like image 184
John R Avatar answered Dec 16 '25 21:12

John R



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!