how to highlight part of textarea html code - javascript

I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight match values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com,but i was a newbie on js,i didn't understand his code meaning.
any advice is appreciated

To save time you should consider using an existing library for this requirement.
Quote from here:
As textarea elements can’t render HTML, this plugin allows you to highlight text inside textarea elements.
jQuery highlightTextarea.
Demo: Codepen
Usage:
$context.highlightTextarea(options);

There is a pre element over the textarea. So when you type anything it is copying the input on the pre element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code it is copying the value, applying filters and adding the HTML to the #view.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex would be a method to match the regex and return some parsed content to the pre, allowing you to customize the appearance of the textarea (that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}

#BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:
http://garysieling.github.io/jquery-highlighttextarea/

Related

Apply style on insert into div

I'm building a search by tags input box as seen here:
http://jsfiddle.net/Newtt/7nUAf/
Forgive the terrible styling as this is just a small component of a larger application and I've just added the styles needed to show my issue.
My search box is a div that has it's text inserted using Jquery as follows:
$(document).ready(function () {
$('.search-box').click(function () {
$('.search-options').toggle();
});
$('.options').click(function () {
var d = $('.search-box').html();
console.log(d);
var c = $(this).html();
console.log(c);
if (d != '') {
$('.search-box').html(d + ', ' + c);
} else {
$('.search-box').html(c);
}
$('.search-options').hide();
});
$('#reset').click(function () {
$('.search-box').html('');
});
});
where .search-box is the input div, .options are the clickable options from the drop down box search-options.
Currently, the text of each option is inserted into the search-box div. I need this to be styled dynamically while it enters the search box.
I tried something on the lines of:
$('<span>').addClass('tag').append(
$('<span>').text(value).append(' '),
$('<a>', {
href : '#',
title : 'Removing tag',
text : 'x'
});
where the tag class is defined in the style sheet to style the element to look like a tag,
but this doesn't work at all. Can someone help me out with how to achieve styling the input text to look like a tag from, say, Evernote notebooks?
Thanks!
I adapted your fiddle. Just wrap c in a span with a class (like you were trying to do in the second part of your post) and apply styles in css. I have just made the background red, but it should be easy enough to make it look like a tag like the ones in the drop down do.
http://jsfiddle.net/7nUAf/1/
JS:
$('.options').click(function () {
var d = $('.search-box').html();
var c = $(this).html();
$('.search-box').append('<span class="tag">'+c +'</span>');
$('.search-options').hide();
});
CSS:
.tag {
background: red;
}
For what you are looking to do - there are lots of excellent plug ins already available that provide much "prettier" functionality and with much less work on your part. Some have already been suggested in the comments - I might suggest consider using "chosen". The syntax is amazingly simple. Just create a select box as follows:
<select id="test" multiple>
<option>pdf</option>
<option>document</option>
</select>
Then in your document ready function you simply need to call chosen plugin:
$(document).ready(function () {
$('#test').chosen({width: "80%"});
});
I put together an example that does this on JSFiddle here: http://jsfiddle.net/7nUAf/3/. Once you get to the point that you have it working you can easily style the elements by inspecting what elements chosen is creating. For example the "li.search-choice" selector will allow you to style the selected items.
In General - even if you don't like this particular plug in, always consider running a search for existing items that do what you are looking for. In the case that these aren't perfect you can always improve them and provide that insight back to the community as a whole. In that way, everyone learns together.
Best of luck!

Can jQuery or Javascript change elements within textareas?

My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/

How to find the selection text beginning and end positions in Javascript?

I am trying to find the textual start and end of the selection. So, in the following text, if I selected "world! What a fine" from within "Hello, world! What a fine day it is!", I should get 7 as the start coordinate, and 24 as the end coordinate assuming a zero based index.
How is this achievable?
EDIT:
I am looking to find the selection of text that is not inside any <input> or <textarea> elements.
EDIT:
Decided the solution to use disabled <textarea>s
I use this:
/* Returns 3 strings, the part before the selection, the part after the selection and the selected part */
function getSelected()
{
var u = editor.val();
var start = editor.get(0).selectionStart;
var end = editor.get(0).selectionEnd;
return [u.substring(0, start), u.substring(end), u.substring(start, end)];
}
where editor is $("#editor") or whatever ID your textarea / input field may have.
Usage:
var select = getSelected()
editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);
Will wrap selected text in H1. If nothing is selected it will just add empty H1, but you can add checks and functionality to your liking.
** Not tested in all browsers, works in Chrome though **
This is possible but slightly complicated with contenteditable HTML content (as opposed to text within an <input> or <textarea> element). Here's a simple cross-browser implementation:
https://stackoverflow.com/a/4812022/96100
But I know a jQuery plugin that aims your problem and much more - https://github.com/localhost/jquery-fieldselection

How to append text to '<textarea>'?

I have <textarea> where user can type in his message to the world! Below, there are upload buttons... I would love to add link to uploaded file (don't worry, I have it); right next to the text that he was typing in.
Like, he types in 'Hello, world!', then uploads the file (its done via AJAX), and the link to that file is added in next line to the content of <textarea>. Attention! Is it possible to keep cursor (place where he left to type) in the same place?
All that may be done with jQuery... Any ideas? I know that there are method 'append()', but it won't be for this situation, right?
Try
var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');
This took me a while, but the following jQuery will do exactly what you want -- it not only appends text, but also keeps the cursor in the exact same spot by storing it and then resetting it:
var selectionStart = $('#your_textarea')[0].selectionStart;
var selectionEnd = $('#your_textarea')[0].selectionEnd;
$('#your_textarea').val($('#your_textarea').val() + 'The text you want to append');
$('#your_textarea')[0].selectionStart = selectionStart;
$('#your_textarea')[0].selectionEnd = selectionEnd;
You should probably wrap this in a function though.
You may take a look at the following answer which presents a nice plugin for inserting text at the caret position in a <textarea>.
You can use any of the available caret plugins for jQuery and basically:
Store the current caret position
Append the text to the textarea
Use the plugin to replace the caret position
If you want an "append" function in jQuery, one is easy enough to make:
(function($){
$.fn.extend({
valAppend: function(text){
return this.each(function(i,e){
var $e = $(e);
$e.val($e.val() + text);
});
}
});
})(jQuery);
Then you can use it by making a call to .valAppend(), referencing the input field(s).
You could use my Rangy inputs jQuery plugin for this, which works in all major browsers.
var $textarea = $("your_textarea_id");
var sel = $textarea.getSelection();
$textarea.insertText("\nSome text", sel.end).setSelection(sel.start, sel.end);

Is there a cross-browser css way to decorate only last word in a span block?

I need to show user's list which should look like in the example below:
Helen Burns Edward
Fairfax Rochester Bertha
Antoinetta Mason Adèle
Varens
Is there a way to achieve this without using javascript? Each row should be one span, i.e. <span>Helen</span><span>Burns</span> is not acceptable.
No, there is not. You are going to have to use some form of scripting to accomplish this if you don't want your last names to be in their own tags.
To the browser, each row is an element, and the "words" themselves have no separate meaning as far as CSS is concerned. You must place the words in different tags in order to do what you want.
The browser does not automagically know what part of the name is the last name so you have to add extra markup to achieve what you want.
There's no solution for common used browser for know using only CSS. You should use javascript or HTML + CSS as you already made.
without pure css this is impossible (as you don't want a separation in the markup)...
<span>Monty Burns</span><br />
<span>Bart Simpson</span>
<script type="text/javascript">
$(document).ready(function() {
var spans = $('span');
spans.each(function(index, element) {
var span = $(element);
var spanText = span.text();
var spanTextArray = spanText.split(' ');
var spanTextArrayLength = spanTextArray.length;
var lastName = spanTextArray[spanTextArrayLength -1];
spanTextArray.pop();
var firstName = spanTextArray.join(' ');
span.text(firstName);
var spanLastName = $('<span/>');
spanLastName.css('font-weight', 'bold');
spanLastName.css('margin-left', '5px');
spanLastName.appendTo(span);
spanLastName.text(lastName);
});
});
</script>
working demo.
edit: if you do not want an extra span-tag in there, just change
var spanLastName = $('<span/>');
spanLastName.css('font-weight', 'bold');
to
var spanLastName = $('<strong/>');
I don't think this is possible with CSS because your example doesn't show any order:
Helen Burns
Edward Fairfax Rochester
Bertha Antoinetta Mason
Adèle Varens
I don't know why you might desire not to have an extra tag surrounding the last name (as other answers and comments have suggested), but if you are looking simply for minimalist mark-up, this works (no span even used):
Html:
<body>
First Middle <strong>Last</strong>
First Middle <strong>Last</strong>
First Middle <strong>Last</strong>
</body>
Css:
strong:after {content:' '; display: block;}
Which creates "rows" with your desired styling without anything more than a single tag (which could be a span rather than a strong if you desired).
Edit: Of course, this will not work for IE7 or under.

Categories

Resources