samedi 21 février 2015

Inserting char into active form element where cursor is focused


I have a few form fields and want to insert clicked character into it(exact position of cursor) but the cursor can be focused on any form field. So if I click a and the cursor between 1 and 2 of text element the result should be 1a23


So far (with my very limited jQuery knowledge) I did easy bit which correctly gets what char was clicked but getting id of active field element returns undefined so I cannot go any further.


This one http://ift.tt/1uXWd5Y specifies the field ID so I couldn't really work out how to inspire from it.


This is my jsfiddle which is half done.


HTML



<div id="chars">
<ul>
<li>a</li>
<li>b</li>
</ul>
</div>
<br />
<input type='text' name='title' value="123" id="titleField" />
<br />
<textarea name='message'id="messageField">456</textarea>


JQUERY



$(document).ready(function() {
$('#chars ul li').click(function(event) {
event.preventDefault();

// this is fine
var char = $(this).text();
console.log(char);

// these returns undefined
console.log($(':focus').attr('id'));
console.log($(document.activeElement).attr('id'));
console.log($(this).parents('.item').attr('id'));

// update 'element' content here by inserting 'char'
});
});




Aucun commentaire:

Enregistrer un commentaire