HTML Appearing as Text in Oracle Apex when Highlighting Text in Textarea - javascript

I have a requirement for the user to highlight text as blue in a text area.
The html is not being applied to the text area and is instead printed as text.
Has anyone encountered and overcome this?
Thank you.
This is the code that I am using:
function ModifySelection () {
var textarea = document.getElementById("P85_30DAY");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
//var newText = textarea.value.substring (0, textarea.selectionStart) +
// "[start]" + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
// textarea.value.substring (textarea.selectionEnd);
var opnSpan = '<span style="color:white;background-color:blue">';
var clseSpan = '</span>';
var begText = textarea.value.substring (0, textarea.selectionStart);
var endText = textarea.value.substring (textarea.selectionEnd);
var selText = opnSpan + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + clseSpan;
//$("#P85_30DAY").html("<span>" + begText + "<span style='color:white;background-color:blue'> " + selText + "</span>" + endText + "</span>"); //appears as text
// textarea.value = begText + selText + endText; //appears as text
$("#P85_30DAY").val(begText + selText + endText); //appears as text
}
}
else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange ();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement ();
if (rangeParent === textarea) {
textRange.text = "[start]" + textRange.text + "[end]";
}
}
}
document.getElementById("P85_30DAY").onkeyup = ModifySelection;
document.getElementById("P85_30DAY").onmouseup = ModifySelection;
This is the html for the element I am trying to highlight text in:
<textarea name="p_t07" class="textarea" id="P85_30DAY" style="width: 587px; height: 600px; font-size: 130%; margin-top: -431px; margin-left: -1340px; position: relative;" contenteditable="true" maxlength="4000" rows="1" cols="80" wrap="virtual"></textarea>

You can't use HTML inside of a textarea. It's an input field and will render anything inside of it as plain text.
Instead, have a look at ContentEditable which will allow you to render HTML inside of an editable element.

I got it to work folks.
Only one highlight selection can be made. I will keep working it but if anyone has any ideas for multiple highlight selection feel free to contribute.
$("#P85_30DAY").attr("contenteditable","true");
$("#P85_30DAY").css("postition","absolute");
function ModifySelection () {
var textarea = document.getElementById("P85_30DAY");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
//var newText = textarea.value.substring (0, textarea.selectionStart) +
// "[start]" + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
// textarea.value.substring (textarea.selectionEnd);
var opnSpan = '<span style="color:white;background-color:blue">';
var clseSpan = '</span>';
var begText = textarea.value.substring (0, textarea.selectionStart);
var endText = textarea.value.substring (textarea.selectionEnd);
// var selText = opnSpan + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + clseSpan;
var selText = textarea.value.substring (textarea.selectionStart, textarea.selectionEnd);
//$("#P85_30DAY").html("<span>" + begText + "<span style='color:white;background-color:blue'> " + selText + "</span>" + endText + "</span>"); //appears as text
// textarea.value = begText + selText + endText; //appears as text
// $("#P85_30DAY").html(begText + $("<span style='color:white;background-color:blue'></span>").text(selText) + endText); appears as object
//$("#P85_30DAY").val(begText + $("p").wrapInner("<span style='color:white;background-color:blue'></span>") + endText); appears as object
$("#P85_30DAY").empty(); //works for one highlight
$("<span>" + begText + "<span style='color:white;background-color:blue'>" + selText + "</span>" + endText + "</span>").appendTo("#P85_30DAY");
}
}
else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange ();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement ();
if (rangeParent === textarea) {
textRange.text = "[start]" + textRange.text + "[end]";
}
}
}
//document.getElementById("P85_30DAY").onkeyup = ModifySelection;
document.getElementById("P85_30DAY").onmouseup = ModifySelection;

Related

Google Docs Apps Script getBackgroundColor(Offset)

Let's say I have some sentences in Google Docs. Just one sentences as an example:
"My house is on fire"
I actually changed the background color so that every verb is red and every noun blue.
Now I want to make a list with all the verbs and another one with the nouns. Unfortunately getBackgroundColor() only seems to work with paragraphs and not with single words.
My idea was, to do something like this (I didn't yet have the time to think about how to do the loop, but that's not the point here anyway):
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor(); // The regEx matches the first word. Next I want to get the background color.
Logger.log(colorVar);
}
The error message I get goes something like this:
"The function getBackgroundColor in the text object couldn't be found"
Thx for any help, or hints or comments!
You want to retrieve the text from a paragraph.
You want to retrieve each word and the background color of each word from the retrieved the text.
In this case, the color is the background color which is not getForegroundColor().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
At first, the reason of your error is that getBackgroundColor() is the method of Class Text. In your script, getBackgroundColor() is used for the string value. By this, the error occurs.
In this answer, for achieving your goal, each character of the text retrieved from the paragraph is scanned, and each word and the background color of each word can be retrieved.
Sample script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var textObj = paragraphs[0].editAsText();
var text = textObj.getText();
var res = [];
var temp = "";
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c != " ") {
temp += c;
} else {
if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
temp = "";
}
}
Logger.log(res) // result
}
When you run the script, the text of 1st paragraph is parsed. And you can see the result with res as an object.
In this sample script, the 1st paragraph is used as a test case. So if you want to retrieve the value from other paragraph, please modify the script.
References:
getBackgroundColor()
getBackgroundColor(offset)
editAsText()
If I misunderstood your question and this was not the direction you want, I apologize.
Here's a script your welcome to take a look at. It highlights text that a user selects...even individual letters. I did it several years ago just to learn more about how documents work.
function highLightCurrentSelection() {
var conclusionStyle = {};
conclusionStyle[DocumentApp.Attribute.BACKGROUND_COLOR]='#ffffff';
conclusionStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
conclusionStyle[DocumentApp.Attribute.FONT_FAMILY]='Calibri';
conclusionStyle[DocumentApp.Attribute.FONT_SIZE]=20;
conclusionStyle[DocumentApp.Attribute.BOLD]=false;
conclusionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
conclusionStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT]=DocumentApp.VerticalAlignment.BOTTOM;
conclusionStyle[DocumentApp.Attribute.LINE_SPACING]=1.5;
conclusionStyle[DocumentApp.Attribute.HEIGHT]=2;
conclusionStyle[DocumentApp.Attribute.LEFT_TO_RIGHT]=true;
var br = '<br />';
var selection = DocumentApp.getActiveDocument().getSelection();
var s='';
if(selection) {
s+=br + '<strong>Elements in Current Selection</strong>';
var selectedElements = selection.getRangeElements();
for(var i=0;i<selectedElements.length;i++) {
var selElem = selectedElements[i];
var el = selElem.getElement();
var isPartial = selElem.isPartial();
if(isPartial) {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:true selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor(selStart)=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(selStart, selEnd, bgcolor)
}else {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:false selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor()=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(bgcolor);
}
var elType=el.getType();
s+=br + 'selectedElement[' + i + '].getType()= ' + elType;
if(elType==DocumentApp.ElementType.TEXT) {
var txt = selElem.getElement().asText().getText().slice(selStart,selEnd+1);
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + 'Type:<strong>TEXT</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span>';
s+=br + 'Length: ' + txt.length;
s+=br + '<div id="sel' + Number(i) + '" style="display:none;">';
for(var key in elattrs)
{
s+= br + '<strong>' + key + '</strong>' + ' = ' + elattrs[key];
s+=br + '<input type="text" value="' + elattrs[key] + '" id="elattr' + key + Number(i) + '" />';
s+=br + '<input id="elattrbtn' + Number(i) + '" type="button" value="Save Changes" onClick="setSelectedElementAttribute(\'' + key + '\',' + i + ');" />'
}
s+='</div>Show/Hide';
}
}
if(elType==DocumentApp.ElementType.PARAGRAPH) {
var txt = selElem.getElement().asParagraph().getText();
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + '<strong>PARAGRAPH Attributes</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span> Text Length= ' + txt.length;
for(var key in elattrs)
{
s+= br + key + ' = ' + elattrs[key];
}
}
}
s+='<hr width="100%"/>';
}
//var finalP=DocumentApp.getActiveDocument().getBody().appendParagraph('Total Number of Elements: ' + Number(selectedElements.length));
//finalP.setAttributes(conclusionStyle);
}else {
s+= br + 'No Elements found in current selection';
}
s+='<input type="button" value="Toggle HighLight" onclick="google.script.run.highLightCurrentSelection();"/>';
//s+='<input type="button" value="Exit" onClick="google.script.host.close();" />';
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(800).setHeight(450).setTitle('Selected Elements'));
}

JavaScript not able to replace text with new text

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)

Setting text input as a variable in Javascript

I'm trying to use my text input as a string variable and use that variable as a part of a URL to pull up JSON data but I can't seem to get it to work properly.
I don't know if I'm setting the variables incorrectly but any help would be appreciated. Thank you!
$(document).ready(function() {
var p = document.querySelector('p');
var input = document.getElementById('search').value;
$("#go").click(function() {
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
} else {
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + input + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
} else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
At the time you assign the variable value, it is empty because it is run when the site is loaded and there is probably no text in the search box yet. You want the content at the time #go is clicked, so just assign it inside the click event handler:
$(document).ready(function() {
var p = document.querySelector('p');
// the text field value is empty at this point
$("#go").click(function() {
// this is run when user clicks #go
var input = document.getElementById('search').value;
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
}
else {
// encode user input
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + encodeURIComponent(input) + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
}
else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
Additionally, you should always encode user input if you include it in a URI. Otherwise you'll experience unexpected behaviour when using any non alphanumerical character (including whitespace) in the search box. For a more detailed explanation of how and why, see the documentation.

modifying value of input text box after clicking on a check box

I have a function where I read the the text input value and update a counter which is displayed in another div. In some cases I show a check box along with text input field. At the moment when user select the check box the amount which is entered in the text input field is doubled and the result is showing in the counter correctly.
What am I trying to achieve id when the user select the check box the input field should be doubled along with the counter.
The text input in the betslip is added dynamically. So there might be more individual betlsips with check boxes in the view.
Here is my code (HTML view is generated dynamically through JS)
BetSlip.prototype.createSingleBetDiv = function(divId, Bet, winPlaceEnabled) {
document.betSlip.setSingleCount($('[name=singleBet]').length);
var id = divId.replace('_div','');
// If such bet already exists
if (!document.betSlip.singleDivExists(divId) && document.betSlip.getSingleCount() < maxNumberInBetslipRacing) {
var singleBetPosition = (Bet.position == null) ? '' : Bet.position;
var raceInfo = Bet.categoryName + ', ' + raceFullName + ' ' + Bet.name + ', ' + Bet.betTypeName + ' (' + Bet.value.toFixed(2) + ')';
var div = $('<div name="singleBet" class="bet gray2" id="' + divId + '"/>')
// Appending div with data
.data('Bet', Bet)
// Appending error element
$(div).append($('<p id="' + divId + '_error" style="display:none;"/>')
.addClass('alert alert-danger alert-dismissable'))
// Appending info element
$(div).append($('<p id="' + divId + '_info" style="display:none;"/>')
.addClass('alert alert-success alert-dismissable'))
var bgDiv = $('<div id="bgDiv"/>').appendTo(div)
// Append left part
var productName = (Bet.productName != null) ? getBrandBetName(Bet.productName) : Bet.betTypeName;
var leftDiv = $('<div class="left"/>')
.appendTo(div)
// Info abt the bet
.append($('<p class="title"><b>' + singleBetPosition + ' ' + Bet.horseName + '</b><span style="float:right">' + productName + '</span></p>'))
.append($('<p class="title">' + raceInfo + '</p>'))
.append($('<p/>')
.addClass('supermid')
// Creating input field
.append($('<input type="text" id="' + id + '_input"/>')
.keypress(function(event) {validateInputs(event, 'decimal')})
.keyup(function() {document.betSlip.updateSinglesTotalPrice()})))
// Creating WIN / PLACE checkbox selection
if (winPlaceEnabled) {
$(leftDiv).append($('<p><input name="winPlaceCheckBox" id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>')
.click(function() {document.betSlip.updateSinglesTotalPrice()}))
}
// Append Done and Reuse btns
$(leftDiv).append($('<a id="reuseBtn" class="button confirm gray reuse" style="display: none;"/>').html(reuse).click(function() {document.betSlip.reuseBet(divId)}))
$(leftDiv).append($('<a id="doneBtn" class="button confirm red donebtn" style="display: none"/>').html(done)
.click(function(){$('#' + divId).find('a.right.orange').click()}))
// Append right part
$(div).append($('<a class="right orange"/>')
.click(function() {
document.betSlip.removeSingleBetDiv(divId);
})
// Closing btn
.append($('<div class="icon_shut_bet"/>')))
// Add div to the bet slip map
document.betSlip.addSingleDiv(divId, div);
return div;
}
else {
if(this.getSingleCount() < maxNumberInBetslipRacing){
$("#betSlipError").show();
$("#betSlipError").html(sameBet);
return null;
}
else{
$("#betSlipError").show();
$("#betSlipError").html(maxBet);
return null;
}
}
}
In the win/place check box I am calling a function which take cares of updating the final price in the counter (Total bet). I would like to update the same in the input text field as well (double up the input value). In case check box is deselected the input amount should be half (both in input field as well as in the counter).
Function which updated the total bet value
BetSlip.prototype.updateSinglesTotalPrice = function() {
var totalBet = 0;
$('[name=singleBet]').each(function() {
var inputValue = $(this).find('input:text').val();
// Win / Place
if (document.betSlip.checkWinPlace(this)) totalBet += Number(inputValue * 2);
// Win or Place
else totalBet += Number(inputValue);
});
$("#betSinglesTotalBet").html(replaceParams(totBetPrice, [totalBet.toFixed(2), document.betSlip.getCurrency()]));
}

Insert text before and after the selection in a textarea with JavaScript

How can I insert text before and after the selection in a textarea with JavaScript?
Selection occurs into a textarea field of an HTML form.
Her us a simple script that works in both Internet Explorer, Firefox, and Chrome, where myField is a object reference. It was assembled by several scripts found through the web.
function insertAtCursor(myField, myValueBefore, myValueAfter) {
if (document.selection) {
myField.focus();
document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;
} else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValueBefore + myField.value.substring(startPos, endPos) + myValueAfter + myField.value.substring(endPos, myField.value.length);
}
}
Try the following:
var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";
If you want to search and replace, then the following code will do the trick (in non-Internet Explorer browsers):
var textBeforeSelection = yourTextarea.value.substr(0, yourTextarea.selectionStart);
var textAfterSelection = yourTextarea.value.substr(yourTextarea.selectionEnd, yourTextarea.value.length);
yourTextarea.value = textBeforeSelection + " new selection text " + textAfterSelection;

Categories