2

Based on the current cursor/textbox selected , when the user clicks a button/character I would like the character to be inserted where the cursor is.

Here is a js fiddle example:

http://jsfiddle.net/YD6PL/32/

JS:

$(document).ready(function () {
    $(".buttons").click(function () {
        var cntrl = $(this).html();
        $("#txt-area1").append(cntrl);//not sure what to use here to "know" where cursor currently is
    });
});

HTML:

<textarea id="txt-area1" readonly></textarea>
<textarea id="txt-area2" readonly></textarea>
<textarea id="txt-area3" readonly></textarea>
<textarea id="txt-area4" readonly></textarea>
<div>
<button class="buttons">á</button>
<button class="buttons">é</button>
<button class="buttons">í</button>
<button class="buttons">ó</button>
<button class="buttons">ú</button>
<button class="buttons">ñ</button>
<button class="buttons">ü</button>
</div>

How can I make the above "know" which of the multiple text boxes is selected and insert the character only into this box?

1
  • How about when an element is focused append a class active, when it losses focus remove that class. Then You can append the text box with the active class. Commented Sep 5, 2014 at 18:31

3 Answers 3

4

Add a class of active to a clicked textarea and select that active textarea when you append.

$('textarea').click(function(){
    $(this).addClass('active').siblings('.active').removeClass('active')
});

$(".buttons").click(function () {
    var cntrl = $(this).html();
    $('textarea.active').append(cntrl);
});

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

What a quick answer. I had the same idea but wow, you thought of it and implemented as fast as I just thought about it.
1

Use focus event on textarea:

$(document).ready(function () {

    var selected = undefined;

    $('textarea').on('focus', function(){
        selected = $(this)
    })

    $(".buttons").click(function () {
        if(selected) {
            var cntrl = $(this).html();
            selected.append(cntrl);
        }
    });
});

jsFiddle Demo

Comments

0
var currentDiv;

$(document).ready(function () {
    $(".buttons").click(function (el) {
        var cntrl = $(this).html();

        $(currentDiv).append(cntrl);
    });
});

$("#parent").click(function(e) {
    currentDiv = e.target
});

1 Comment

Could you improve your answer by explaining what you fixed?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.