I have a form with numerous inputs/textareas, the admin using the form can add dynamic values into the text e.g: page title = "Hi {name}, welcome to {shop_name}". At the bottom of the form I have a list of all the available dynamic values.
Q: What I am trying to do is on click of a value in the list, it finds out the previous input on focus and inserts the value.
More simple put how would I make this jsFiddle work for this input=text the same as it does for the textarea? So if I had my cursor in the input field it would add the foo value there instead of the textarea.
HTML
<form action="" method="post">
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="message">Message:</label>
<textarea name="message">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </textarea>
<input value="Submit" type="submit" />
</form>
<h3>Insert short code</h3>
<ul class="inserts">
<li><a href="#" data-foo="{foo_1}">Foo 1</a></li>
<li><a href="#" data-foo="{foo_2}">Foo 2</a></li>
<li><a href="#" data-foo="{foo_3}">Foo 3</a></li>
<li><a href="#" data-foo="{foo_4}">Foo 4</a></li>
<li><a href="#" data-foo="{foo_5}">Foo 5</a></li>
</ul>
JS
jQuery.fn.extend({
insertAtCaret: function (myValue) {
return this.each(function (i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
} else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
}
});
$(".inserts a").click(function (e) {
e.preventDefault();
$('textarea').insertAtCaret(
$(this).data("foo")
);
});