<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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With