Jquery event fired multiple times

In the following code, why does the trigger fire three times after this? "Text marked!" added three times after input.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("input").select(function(){
        $("input").after(" Text marked!");
    });
    $("button").click(function(){
        $("input").trigger("select");
    });
});
</script>
</head>
<body>

<input type="text" value="Hello World"><br><br>

<button>Trigger the select event for the input field</button>

</body>
</html>
+4
source share
1 answer

I can confirm that this happened to me in Chrome. Im really not sure why, but you can fix it by adding event.preventDefault().

$("input").select(function(event){
  event.preventDefault();
  $("input").after(" Text marked!");
});

Demo: http://jsbin.com/yedoxov/edit?html,js,output

+5
source

Source: https://habr.com/ru/post/1628751/


All Articles