I'm making a a simple texteditor and for that I'm using a function which gets the selected text of a textarea.
My problem is not getting the selected text but when i add some tags to the selected text, for example bold or italic, it appends. So what I want is to delete the selection first before adding it to the textarea.
Here's my code:
<input type="button" id="bold" value="BOLD"/>
<input type="button" id="undo" value="UNDO"/>
<textarea id="message" cols="50" rows="20"></textarea>
var text = [];
var textarea = document.getElementById('message');
//simple texteditor
function edit(tag) {
var startPos = textarea.selectionStart;
var endPos = textarea.selectionEnd;
var selection = textarea.value.substring(startPos, endPos);
var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">");
textarea.value += surrounder;
updatePreview();
textarea.focus();
}
document.getElementById('bold').onclick = function () {
edit('b');
};
document.getElementById('undo').onclick = function () {
document.execCommand('undo',false,null);
};
thanks in advance!
I think this works for you:
var text = [];
var textarea = document.getElementById('message');
//simple texteditor
function edit(tag) {
var startPos = textarea.selectionStart;
var endPos = textarea.selectionEnd;
console.log(startPos);
var selectionBefore = textarea.value.substring(0, startPos);
var selection = textarea.value.substring(startPos, endPos);
var selectionAfter = textarea.value.substring(endPos);
var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">");
var newText = selectionBefore + surrounder + selectionAfter;
textarea.value = newText;
updatePreview();
textarea.focus();
}
document.getElementById('bold').onclick = function () {
edit('b');
};
document.getElementById('undo').onclick = function () {
document.execCommand('undo',false,null);
};
https://jsfiddle.net/3L659v65/
Related
I am trying to convert selected text's font with help of AngularJs and jQuery. This is my code. Everything is working fine but i am not able to change the text with a new text.
This is my code:
var app = angular.module('myApp', []);
app.controller('editor', function($scope) {
$scope.color = "black";
$scope.selectedText = "";
$scope.changeFont = function() {
if ($scope.selectedText != "") {
var changedText = "<span style='font-size:" + $scope.kys_selected_font + "px' >" + $scope.selectedText + "</span>";
alert($scope.selectedText + $scope.kys_selected_font + " " + changedText);
document.getElementById("#content").innerHTML.replace($scope.selectedText, changedText);
} else {
$("#content").append("<span id='one' style='font-size:" + $scope.kys_selected_font + "px' > this is some text </span>");
$("#one").focus();
}
};
$("#content").mouseup(function() {
$scope.selectedText = window.getSelection();
});
});
innerHTML.replace(...) returns a new string, rather than modifying the existing one, so your replacement won't modify the element.
You need to actually update the property:
var el = document.getElementById("content");
el.innerHTML = el.innerHTML.replace($scope.selectedText, changedText);
(also note # removed from element ID as per #IvanSivak's comment)
I have the following code i would like to insert bodytext variable into anchor tag how to achieve this
function blogBodyRenderer(ctx) {
var item = ctx.CurrentItem;
var html = item['Body'];
var plainBodyText = $(html).text();
var res = plainBodyText.substring(0, 15);
alert(res);
var str2 = 'Read more...';
var bodytext = res.concat(str2);
return ' + bodytext + ';
}
You are not properly closing the string. Try this
'' + bodytext + '';
I have to create:
1 <input type="text">
1 <textarea>
1 <div>
1 <button>
I have to fill the div with the textarea's content but if the content contains the input's string, I have to color it with <span>.
For example:
If the input contains "is" and the textarea contains "this is a beautiful day", I should put the following text in the div "this is a beautiful day" and color every time that the "is" string appears.
I should use indexOf() and a loop.
I have this:
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
if (x > -1)
If you absolutely have to use indexOf
while(b.indexOf(a) != -1) {
b = b.replace(a, '[X]');
}
while(b.indexOf('[X]') != -1) {
b = b.replace('[X]', '<span style="color:yellow;">' + a + '</span>');
}
$("#targetDiv").html(b);
You can also do this with RegExp
var a = $("#inp1").val();
var b = $("#txt").val();
var re = new RegExp(a, 'g');
var divContent = b.replace(re, '<span style="color:yellow;">' + a + '</span>');
$("#targetDiv").html(divContent);
Here is a fiddle with the indexOf
http://jsfiddle.net/eva3ttuL/1/
Here is the code to find and change color of all searched word
$(document).ready(function () {
$("#here").on("keydown keyup", function () {
var mytext = $(this).val();
var find = $("#find").val();
mytext=mytext.replace(new RegExp(find,"g"), "<span class='me'>"+find+"</span>");
$("#output").html(mytext);
});
})
.me{color: #00f;
background-color: #EFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="find" type="text" /><br/>
<textarea id="here"></textarea><br/>
<div id="output"></div>
Use JavaScript substring to split the string inside textarea and form a paragraph with the highlighted text.
HTML code:
<input id="inp1" type="text"/><br>
<textarea id="txt" col="10" row="5"></textarea><br>
<div id="fillarea">
click on check
</div>
<button id="check">check</button>
CSS for highlighting:
.highlight{
background-color:yellow;
}
jQuery code:
$('#check').on('click',function(){
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
var first = b.substring(0,x);
var middle = b.substring(x,x+a.length);
var last = b.substring(x+a.length,b.length);
var to_print = '<p>' + first + '<span class="highlight">' + middle + '</span> ' + last + '</p>';
$('#fillarea').empty();
$('#fillarea').append(to_print);
});
Demo fiddle here
It helps you jsfiddle
$('.submit').click(function(){
var content = $('.textarea').val();
var ans = content.replace($('.input').val(), "<span style='color:red;'>"+$('.input').val()+"</span>");
$('.text').html(ans);
});
var input = $("#inp1").val();
var text = $("#txt").val();
var div = $("#div");
div.val(text.replace(new RegExp(input,'g'), makeSpan(input)));
function makeSpan(str) {
return '<span style="background-color:red">' + str + '</span>';
}
Just try this
<html>
<title></title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var a = "is";
var b = "this is beautiful";
var x = b.indexOf(a);
if (x > -1) {
var re = new RegExp(a, 'g');
res = b.replace(re, "<span style='color:red'>"+a+"</span>" );
$("#result").html(res);
}
})
</script>
</head>
<body>
<div id="result"></div>
</body>
You can use IndexOf Javascript function
var str1 = "ABCDEFGHIJK";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
OK I am attempting to use onchange to capture the value from a dropbx but while I select the the value in the box it never seems to catch the onchange and I get an undefined value for the variable I try and capture the change with. I popped print statement into the onchange function call and it never seems to pick up the value switch. Any help is greatly appreciated
newWindow = window.open("", null, "height=400,width=800,status=yes,toolbar=no,menubar=no,location=no");
newWindow.document.title = "Crafting Window";
newWindow.document.body.style.background = "#00214D";
newWindow.document.body.style.color = "White";
// create a form and set properties
var form = document.createElement('form');
form.method = 'post';
// insert into the body of the new window
newWindow.document.body.appendChild(form);
// add text before the input
var cNumLab = document.createElement('cNumLab');
form.appendChild(document.createTextNode('Craft Number:'));
// add a text input
var cNum = document.createElement('input');
cNum.type = 'text';
cNum.name = 'input';
cNum.value = '';
form.appendChild(cNum);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var sDescL = document.createElement('sDescL');
form.appendChild(document.createTextNode('Short Desc:'));
// add a text input
var sDesc = document.createElement('input');
sDesc.type = 'text';
sDesc.name = 'sDesc';
sDesc.value = '';
sDesc.size = 50;
form.appendChild(sDesc);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var lDescL = document.createElement('lDesc');
form.appendChild(document.createTextNode('Long Desc:'));
// add a text input
var lDesc = document.createElement('input');
lDesc.type = 'text';
lDesc.name = 'lDesc';
lDesc.value = '';
lDesc.size = 80;
form.appendChild(lDesc);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eDescL = document.createElement('eDescL');
form.appendChild(document.createTextNode('Extended Desc:'));
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add a text input
var eDesc = document.createElement('textarea');
eDesc.type = 'text';
eDesc.name = 'eDesc';
eDesc.value = '';
form.appendChild(eDesc);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eTools = document.createElement('eTools');
form.appendChild(document.createTextNode('Tools:'));
// add a text input
var eTool = document.createElement('input');
eTool.type = 'text';
eTool.name = 'eTools';
eTool.value = '';
form.appendChild(eTool);
var tools = document.createElement('select');
tools.id = 'sTools';
tools.name = 'sTools';
form.appendChild(tools);
var cTool;
var e = document.getElementById("sTools");
var options = [
["Forge 33", "33"],
["Workbench 1391", "1391"],
["Oven 1753", "1753"],
["Mortar-Pestle 3277", "3277"],
["Chisel 3349", "3349"],
["Pottery Wheel 3420", "3420"],
["Kiln 3421", "3421"],
["Blowpipe3422", "3422"],
["Bookbinder 3467", "3467"],
["Palette 3483", "3483"]
];
for (var i = 0; i < options.length; i++) {
var opt = document.createElement('option');
opt.appendChild(document.createTextNode(options[i][0]));
opt.value = options[i][1];
tools.appendChild(opt);
}
tools.onchange = function () {
print("GOT HERE");
cTool = e.options[e.selectedIndex].value;
alert(cTool);
};
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eIngreds = document.createElement('eIngreds');
form.appendChild(document.createTextNode('Ingredients:'));
// add a text input
var eIngred = document.createElement('input');
eIngred.type = 'text';
eIngred.name = 'eIngred';
eIngred.value = '';
eIngred.size = 50;
form.appendChild(eIngred);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps1 = document.createElement('eSteps1');
form.appendChild(document.createTextNode('Step 1:'));
// add a text input
var eStep1 = document.createElement('input');
eStep1.type = 'text';
eStep1.name = 'eStep1';
eStep1.value = '';
eStep1.size = 80;
form.appendChild(eStep1);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps1 = document.createElement('eSteps2');
form.appendChild(document.createTextNode('Step 2:'));
// add a text input
var eStep2 = document.createElement('input');
eStep2.type = 'text';
eStep2.name = 'eStep2';
eStep2.value = '';
eStep2.size = 80;
form.appendChild(eStep2);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps3 = document.createElement('eSteps3');
form.appendChild(document.createTextNode('Step 3:'));
// add a text input
var eStep3 = document.createElement('input');
eStep3.type = 'text';
eStep3.name = 'eStep3';
eStep3.value = '';
eStep3.size = 80;
form.appendChild(eStep3);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps4 = document.createElement('eSteps4');
form.appendChild(document.createTextNode('Step 4:'));
// add a text input
var eStep4 = document.createElement('input');
eStep4.type = 'text';
eStep4.name = 'eStep4';
eStep4.value = '';
eStep4.size = 80;
form.appendChild(eStep4);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps5 = document.createElement('eSteps5');
form.appendChild(document.createTextNode('Step 5:'));
// add a text input
var eStep5 = document.createElement('input');
eStep5.type = 'text';
eStep5.name = 'eStep5';
eStep5.value = '';
eStep5.size = 80;
form.appendChild(eStep5);
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
// add text before the input
var eSteps6 = document.createElement('eSteps6');
form.appendChild(document.createTextNode('Step 6:'));
// add a text input
var eStep6 = document.createElement('input');
eStep6.type = 'text';
eStep6.name = 'eStep6';
eStep6.value = '';
eStep6.size = 80;
form.appendChild(eStep6);
var cTool;
var e = document.getElementById("sTools");
tools.onchange = function () {
cTool = e.options[e.selectedIndex].value;
alert(cTool);
};
//add linebreak
var linebreak = document.createElement('br');
form.appendChild(linebreak);
var eSubmit = document.createElement('button');
eSubmit.type = 'button';
//eSubmit.name = 'Submit Design';
eSubmit.innerHTML = 'Submit Design';
eSubmit.onclick = function () {
if (sDesc.value !== "") {
client.send_direct("craft edit " + cNum.value + " short_desc " + sDesc.value);
}
if (lDesc.value !== "") {
client.send_direct("craft edit " + cNum.value + " long_desc " + lDesc.value);
}
if (eDesc.value !== "") {
client.send_direct("craft edit " + cNum.value + " extended_desc " + eDesc.value);
}
if (eIngred.value !== "") {
client.send_direct("craft ingredients " + cNum.value + " " + eIngred.value);
}
if (eTool.value !== "") {
client.send_direct("craft tools " + cNum.value + " add " + eTool.value);
}
if (eStep1.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 1 1 " + eStep1.value);
}
if (eStep2.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 2 1 " + eStep2.value);
}
if (eStep3.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 3 1 " + eStep3.value);
}
if (eStep4.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 4 1 " + eStep4.value);
}
if (eStep5.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 5 1 " + eStep5.value);
}
if (eStep6.value !== "") {
client.send_direct("craft steps " + cNum.value + " change 6 1 " + eStep6.value);
}
alert(cTool);
};
form.appendChild(eSubmit);
I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code
<script>
function fillin(entire,name,id,key) {
if (entire.checked == true) {
var split_info = new Array();
split_info = name.split(":");
var div = $("#Inputfields"+id);
var till = (div.children("input").length)/4;
var current_count = 0;
for (var j=0;j<till;j++) {
if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") {
document.getElementById("insertname_"+j+"_"+id).value = split_info[0];
document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1];
break;
} else
current_count = current_count+1;
if (current_count == till) {
var x= addnew(id);
x =x+1;
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
document.getElementById("insertname_"+x+"_"+id).text = split_info[0];
//alert(document.getElementById("insertname_"+x+"_"+id).value);
//document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1];
}
}
} else {
}
}
</script>
<script>
function addnew(n) {
//var id = $(this).attr("id");
var div = $("#Inputfields"+n);
var howManyInputs = (div.children("input").length)/4;
alert(howManyInputs);
var val = $("div").data("addedCount");
var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">';
var fin = a+b+d+c;
$(fin).appendTo(div);
div.data("addedCount", div.data("addedCount") + 1);
return howManyInputs;
}
</script>
UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x
The problem is probably here:
document.getElementById("insertname_"+x+"_"+id).text
There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do:
document.getElementById("insertname_"+x+"_"+id).innerHTML = ...
or
$("#insertname_"+x+"_"+id).text(...);
Also, these lines:
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
.value there should be replaced with .val(), because those are jQuery objects.
I have reworked a lot of your code for a lot of reasons. Compare the two.
function fillin(entire, name, id, key) {
if (entire.checked) {
var split_info = [];
split_info = name.split(":");
var div = $("#Inputfields" + id);
var till = (div.children("input").length) / 4;
var current_count = 0;
var j = 0;
for (j = 0; j < till; j++) {
var myj = j + "_" + id;
if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") {
$("#insertname_" + myj).val(split_info[0]);
$("#insertnumber_" + myj).val(split_info[1]);
break;
} else {
current_count = current_count + 1;
}
if (current_count === till) {
var x = addnew(id) + 1;
div.find("#insertname_" + x + "_" + id).val(split_info[0]);
alert(div.find("#insertname_" + x + "_" + id).val());
$("#insertname_" + x + "_" + id).val(split_info[0]);
}
}
}
}
function addnew(n) {
var div = $("#Inputfields" + n);
var howManyInputs = (div.children("input").length) / 4;
alert(howManyInputs);
var myi = (howManyInputs) + '_' + n + '"';
var val = div.data("addedCount");
var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">';
var fin = a + b + d + c;
$(fin).appendTo(div);
div.data("addedCount", val + 1);
return howManyInputs;
}