Fill textarea with clicked button - javascript

SOLVED
http://jsfiddle.net/ArtofLife/u9d9d/
I have multiple TEXTAREA and BUTTON out side.. For inserting string in textarea, I used jQuery plugin (insertAtCaret). How to fill ONLY the last clicked TEXTAREA with text...?
<textarea name="answer_text[0]" cols="50" rows="3" style="width: 99%;">
AAA
</textarea>
<textarea name="answer_text[1]" cols="50" rows="3" style="width: 99%;">
BBB
</textarea>
<textarea name="answer_text[2]" cols="50" rows="3" style="width: 99%;">
CCC
</textarea>
<textarea name="answer_text[3]" cols="50" rows="3" style="width: 99%;">
Here should be:
<button class=insert name=insert>Insert</button>
</textarea>
<button class=insert name=insert>Insert</button>
<script type="text/javascript">
jQuery.fn.extend({
insertAtCaret: function(myValue) {
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
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();
}
});
}
});
var pos = 0;
$('textarea').click(function() {
//Get the name of this clicked item
var pos = $(this).attr("name");
$('.insert').click(function() {
$('textarea[name^="' + pos + '"]').insertAtCaret('Actual button code');
});
return false;
});
</script>
Now I getting filed all the textareas that I clicked... http://jsfiddle.net/ArtofLife/u9d9d/15/
I want to be filled only the last textarea that is clicked, and not bubbling the variable pos..

It is because you have the .insert's click handler inside the textarea click handler. Whenever you click on textarea a new handler is attached and it keeps attaching as and when u click on any textarea. Move it outside it will work fine.
var pos = 0;
$('textarea').click(function() {
//Get the name of this clicked item
pos = $(this).attr("name");
return false;
});
$('.insert').click(function() {
$('textarea[name^="' + pos + '"]').insertAtCaret('Actual button code');
});
Demo

Related

ng-paste and onpaste, how to preserve/get existing text while pasting new text

I'm using ng-paste and onpaste like this,
<input type="text" class="form-control" ng-trim="false" ng-model="x.value" select-on-click ng-paste="paste($event, x)" onpaste="return false;" id="input{{$index}}"
The input has text some<CURSOR>data (where the <CURSOR> represents the position of the cursor)
When I press Cmd + V the paste event is called,
$scope.paste = function(event, data) {
console.log('paste event', event);
}
It works, but I can only get the pasted text, what I want is some<PASTED DATA>data, any ideas?
P.S I had to use onpaste="return false;", otherwise the text become <PASTED DATA><PASTED DATA>
You could use input element's selectionStart/selectionEnd properties to do the trick.
function onPaste(event) {
var input = event.target;
var start = input.selectionStart;
var end = input.selectionEnd;
var originString = input.value;
var myContent = "<PASTED DATA>";
input.value = originString.substring(0, start) + myContent + originString.substring(end, originString.length);
event.preventDefault();
var currentPosition = (originString.substring(0, start) + myContent ).length;
setTimeout(function () {
input.focus();
input.setSelectionRange(currentPosition, currentPosition);
}, 0);
}

Insert HTML in Div with a substr

I am trying to insert an underline or blank space in a div that is being affected with a keyup function. The objective is to be able to move where the blank space is in the text. The keyup function works fine, the inserting of the blank space (div class underline) isnt.
HTML:
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>
Javascript/Jquery:
$(document).ready(function () {
$('#text').keyup(function(){
$('#bigwhitecard').html($(this).val());
});
var blankplace = 0;
$('#rightbtn').click(function() {
blankplace++;
});
$('#leftbtn').click(function() {
blankplace--;
});
var b = '<div class="underline"></div>';
$('#bigwhitecard').each(function() {
var blankplace = 0;
var txt = $(this).text();
if (txt.length>0) {
$(this).html(''+txt.substring(0,blankplace)+'<div class="underline"> </div>');
}
});
});
So use a substr to get the remaining text length that is left over and add it after the text.
var filler = "__________";
var out = document.getElementById("bigwhitecard");
document.getElementById("text").addEventListener("keyup", function() {
var txt = this.value,
placeholder = txt.length<filler.length ? '<span class="underline">' + filler.substr(0,filler.length-txt.length) + '</span>' : '';
out.innerHTML = txt + placeholder;
});
.underline {
text-decoration: underline
}
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>
And based on your comment
var out = document.getElementById("bigwhitecard");
document.getElementById("text").addEventListener("keyup", function() {
var txt = this.value,
ind = 6,
len = this.value.length,
pre = len > ind ? txt.substr(0,ind) : txt,
suf = len > ind ? txt.substr(ind) : "";
out.innerHTML = pre + "<span>_</sapn>" + suf;
});
.underline {
text-decoration: underline
}
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>

Textarea validation by javascript

there are 2 kinds radio buttons.
If check sms button, then textarea's maxlength sets 90 bytes
If check lms button, then testarea's maxlength sets 2000 bytes
and We can check how many I put texts on the textarea at 'totalWordLimit'
but have problems
If I put many texts by copy & paste, textarea become disabled
and also when I change radio buttons, counting number doesn't initialize.
What I need to fix in this code?
<script type="text/javascript">
var setTotalNumberOfWordCounter = "90";
function displayWordCounter(){
var getTextValue = document.smsForm.msg.value; // Get input textarea value
var getTextLength = getTextValue.length; // Get length of input textarea value
var one_char = "";
var rbyte = 0;
var rlen = 0;
for(var i=0; i<getTextLength; i++){
one_char = getTextValue.charAt(i);
if(escape(one_char).length > 4){
rbyte += 2; // special language(2Bytes)
}else{
rbyte++; // 1Byte
}
if(rbyte <= setTotalNumberOfWordCounter){
rlen = i+1; //return text count
}
}
if(rbyte > setTotalNumberOfWordCounter){ //compare this length with total count
getTextValue = getTextValue.substring(0,setTotalNumberOfWordCounter);
document.smsForm.msg.value =getTextValue;
return false;
}
document.smsForm.totalWordLimit.value = (setTotalNumberOfWordCounter-rbyte);
var tt = document.getElementById("Textarea");
if(document.smsForm.totalWordLimit.value === "0"){
tt.value = tt.value.substring(0, tt.value.length-1);
}
}
</script>
<script type="text/javascript">
function ShowHide() {
var Textarea = document.getElementById("Textarea");
if(document.getElementById('sms').checked) {
setTotalNumberOfWordCounter = "90";
}else if(document.getElementById('lms').checked) {
setTotalNumberOfWordCounter = "2000";
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="sms" id="sms" onclick="ShowHide()" value="ss" checked>SMS
<input type="radio" name="lms" id="lms" onclick="ShowHide()" value="ll"> LMS
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" ></textarea>
<script type="text/javascript">
document.write("<div class='total_count'>total remaining Charatctor: <input type='text' class='show_count' name='totalWordLimit' size=4 readonly value="+setTotalNumberOfWordCounter+"></div>");
</script>
Try this one
function ShowHide() {
var Textarea = document.getElementById("Textarea");
if(document.getElementById('sms').checked) {
Textarea.setAttribute("maxlength", "90");
}else if(document.getElementById('lms').checked) {
Textarea.setAttribute("maxlength", "2000");
}
}
and try onpaste function in the textarea element
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" onpaste="return displayWordCounter();"></textarea>

Putting the data clicked by the user in the text field in the pop up using javascript [duplicate]

This question already has answers here:
How to get a word under cursor using JavaScript?
(12 answers)
Closed 7 years ago.
The problem that I am currently dealing with is that the user has to enter the text in a text area and after the entering of the text the user is free to click on any of the text that he entered, the clicked text than has to be displayed the popup .Following is the code that is not working as per the above problem stated.
<p id="msg">roli</p>
<form onload>
<center><label>Enter text:</label><br>
<textarea style="width:100px; height:100px" id="hello" >
</textarea>
</center>
</form>
<script>
var stopCharacters = [' ', '\n', '\r', '\t']
$(function() {
document.getElementById("msg").innerHTML="bhanu";
$('textarea').on('click', function() {
var text = $(this).html();
var start = $(this)[0].selectionStart;
var end = $(this)[0].selectionEnd;
while (start > 0) {
if (stopCharacters.indexOf(text[start]) == -1) {
--start;
} else {
break;
}
};
++start;
while (end < text.length) {
if (stopCharacters.indexOf(text[end]) == -1) {
++end;
} else {
break;
}
}
var currentWord = text.substr(start, end - start);
alert(currentWord);
});
});
</script>
Here you need to create a range for selection
var stopCharacters = [' ', '\n', '\r', '\t'];
$(function() {
document.getElementById("msg").innerHTML="bhanu";
$('textarea').on('click', function() {
var textComponent = document.getElementById('hello');
var currentWord;
// IE version
if (document.selection != undefined){
textComponent.focus();
var sel = document.selection.createRange();
currentWord = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined){
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
while(textComponent.value.charAt(startPos)!=' '){
if(startPos<=0)break;
startPos--;
console.log(startPos);
}
while(textComponent.value.charAt(endPos)!=' '){
if(endPos >= textComponent.value.length)break;
endPos++;
console.log(endPos);
}
currentWord = textComponent.value.substring(startPos, endPos);
}
alert(currentWord);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="msg">roli</p>
<form onload>
<center><label>Enter text:</label><br>
<textarea style="width:100px; height:100px" id="hello" ></textarea>
</center>
</form>
Did you mean like clicking on the same text box will alert the user with the contents of the text box? If so, you don't need any JavaScript or complex stuff which you have done. Click on the below snippet and click on the text box.
var stopCharacters = [' ', '\n', '\r', '\t'];
$(function() {
$("#msg").html("bhanu");
$('textarea').on('click', function() {
if ($(this).val().trim().length == 0)
return;
var textComponent = $(this)[0];
var currentWord;
// IE version
if (document.selection != undefined){
textComponent.focus();
var sel = document.selection.createRange();
currentWord = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined){
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
currentWord = textComponent.value.substring(startPos, endPos)
}
alert(currentWord);
});
});
textarea {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="msg">roli</p>
<form>
<label for="hello">Enter text:</label>
<textarea style="width:100px; height:100px" id="hello" ></textarea>
</form>

Getting the position of the caret in textarea on click

Suppose you have a textarea and a button, and that you wanted that button to get the position of the caret in a textarea, whenever that button was clicked. (I know, there would be a loss of focus from the text area to the button.)
Is there a way to recall where the caret was in the textarea? If so, how would one go about doing that (so that they could, for example, have said button write text to that area)?
Get the position of caret when it loses focus:
var caretStart, caretEnd;
$('#textarea').on('blur', function(e) {
caretStart = this.selectionStart;
caretEnd = this.selectionEnd;
});
To write text when a button was click:
$('#btnWriteText').on('click', function(e) {
var text = " Example ";
var $this = $('#textarea');
// set text area value to: text before caret + desired text + text after caret
$this.val($this.val().substring(0, caretStart)
+ text
+ $this.val().substring(caretEnd));
// put caret at right position again
this.selectionStart = this.selectionEnd = caretStart + text.length;
});
This solution may help you. You can try out,
<html>
<head>
<title>Get/Set Caret in Textarea Example</title>
<script>
function doGetCaretPosition (ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos)
{
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
function process()
{
var no = document.getElementById('no').value;
setCaretPosition(document.getElementById('get'),no);
}
</script>
</head>
<body>
<textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea>
<br>
Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position">
<BR>
<input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));"
value="Get Position">
</body>
</html>
Source: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/

Categories