I have to two textarea
each with same button
class .addText
. I am trying insert word hello world
to the textarea
where the cursor in, this event would trigger via shortcut key ctrl
+ i
.
$(document).ready(function() {
$(window).keydown(function(event) {
console.log(event.keyCode);
if (event.ctrlKey && event.keyCode == 73) {
$(".addText").trigger("click");
event.preventDefault();
}
})
$('.addText').click(function() {
// Add Text 'hello world' to input textarea that curssor currently in
$(this).next().val('hello world');
})
});
<!-- Include BS and FA -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="ta1">
<button class="addText">Add Text</button>
<textarea cols="30" rows="10" class="inputTa1"></textarea>
</div>
</div>
<div class="col-xs-6">
<div class="ta1">
<button class="addText">Add Text</button>
<textarea cols="30" rows="10" class="inputTa2"></textarea>
</div>
</div>
</div>
</div>
However, Currently, the word hello world
is inserted into both textarea when shortcut key ctrl
+ i
is pressed.
I could not differentiate which textarea cursor is currently in, I found one source here: Insert text into textarea at cursor position (Javascript), but it does not apply to my case.
How can I check which textarea that has cursor in and apply an action to it? Thanks.