jQuery putting content of a paragraph in a textarea - javascript

I tried to do this for replacing a paragraph with a text area with the same content.
function edit() {
var wdith = $("p").css('width')
$("p:first").replaceWith("<textarea class='edit'>" + $("p:first").text() + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
Demo
But it doesn't work correctly. There are spaces before and after the text.
How do I fix it?

You script is doing as it says on the tin. You're getting spaces because you have spaces and line breaks within your <p> tags.
To remove the text formatting, try this: http://jsfiddle.net/z9xCm/18/
function edit() {
var wdith = $("p").css('width');
var p = $("p:first");
var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
p.replaceWith("<textarea class='edit'>" + t + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
First, we remove the line breaks, then removed multiple repeated spaces, then trim spaces at the beginning and end of the text.
Somewhat off topic, but that can also be rewritten as : http://jsfiddle.net/z9xCm/52/
$("#replace").click(function() {
var p = $("p:first");
p.replaceWith($("<textarea/>", {
"class": "edit",
"text": p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
"css": { "width": p.css('width') }
}));
});
Here's the same thing, but in a less compact and commented form.
$("#replace").click(function() { /* assign anonymous function to click event */
var p = $("p:first"); /* store reference to <p> element */
/* get p.text() without the formatting */
var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
/* create new textarea element with additional attributes */
var ta = $("<textarea/>", {
"class": "edit",
"text": t,
"css": {
"width": p.css('width')
}
});
p.replaceWith(ta); /* replace p with ta */
});
Note that the $("...", {...}) syntax for creating new elements with attributes was only introduced in jquery 1.4.

You can use the method $.trim() to remove the spaces at the begin and end:
$.trim($("p:first").text());

You could trim each line manually: http://jsfiddle.net/z9xCm/14/.
function edit() {
var wdith = $("p").css('width');
var spl = $("p").text().split("\n");
spl = spl.map(function(v) {
return v.trim();
});
var txt = spl.join(" ").trim();
$("p:first").replaceWith("<textarea class='edit'>" + txt + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);

You're paragraph has leading spaces at the start of each line. These are remaining when you convert it to a textarea. So remove the spaces from the <p> block to fix the issue.
Updated demo
Also remove line breaks if you don't want them to remain.
Updated demo without line breaks either

Use the following with a regular expression replacement (updated Fiddle):
function edit() {
var wdith = $("p").css('width')
$("p:first").replaceWith("<textarea class='edit'>" + $("p:first").text().replace(/[\n\r](\s*)/g," ").trim() + "</textarea>")
$(".edit").css("width", width)
}
$("#replace").click(edit);

Related

Function does not work on second occurence?

I am trying to change the color of multiple texts to a certain color by using this code:
var search = "bar";
$("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).text().replace(regex, "<span class='red'>"+search+"</span>"));
});
However, the code does not work a second time, and I am not sure why--it only changes the newest occurrence of the code.
Here is a JSFiddle using it twice where it is only changing the 2nd occurrence: http://jsfiddle.net/PELkt/189/
Could someone explain why it does not work on the 2nd occurrence?
Could someone explain why it does not work on the 2nd occurrence?
By calling .text() you are removing all the HTML markup, including the <span>s you just inserted.
This is the markup after the first replacement:
<div id="foo">this is a new <span class='red'>bar</span></div>
$(this).text() will return the string "this is a new bar", in which replace "new" with a <span> ("this is a <span class='red'>new</span> bar") and set it as new content of the element.
In order to do this right, you'd have to iterate over all text node descendants of the element instead, and process them individually. See Highlight a word with jQuery for an implementation.
It was easy to fix your jsfiddle. Simply replace both .text() with .html() & you'll see that it highlights new & both bars in red.
jQuery's .text() method will strip all markup each time that it's used, but what you want to do is use .html() to simply change the markup which is already in the DOM.
$(document).ready(function () {
var search = "bar";
$("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).html().replace(regex, "<span class='red'>"+search+"</span>"));
});
search = "new";
$("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).html().replace(regex, "<span class='red'>"+search+"</span>"));
});
});
Here is another way of doing it that will allow you to continue using text if you wish
function formatWord(content, term, className){
return content.replace(new RegExp(term, 'g'), '<span class="'+className+'">'+term+'</span>');
}
$(document).ready(function () {
var content = $('#foo').text();
var change1 = formatWord(content, 'bar', 'red'),
change2 = formatWord(change1, 'foo', 'red');
alert(change2);
$('body').html(change2);
});
http://codepen.io/nicholasabrams/pen/wGgzbR?editors=1010
Use $(this).html() instead of $(this).text(), as $.fn.text() strips off all the html tags, so are the <span class="red">foo</span> stripped off to foo.
But let's say that you apply same highlight multiple times for foo, then I would suggest that you should create a class similar to this to do highlighting
var Highlighter = function ($el, initialArray) {
this._array = initialArray || [];
this.$el = $el;
this.highlight = function (word) {
if (this.array.indexOf(word) < 0) {
this.array.push(word);
}
highlightArray();
}
function highlightArray() {
var search;
// first remove all highlighting
this.$el.find("span[data-highlight]").each(function () {
var html = this.innerHTML;
this.outerHTML = html;
});
// highlight all here
for (var i = 0; i < this._array.length; i += 1) {
search = this._array[i];
this.$el.find("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).html().replace(regex, "<span data-highlight='"+search+"' class='red'>"+search+"</span>"));
});
}
}
}
var highlighter = new HighLighter();
highlighter.highlight("foo");

Add ">" symbol at front of each textarea line using jquery

i don't know how to add this symbol '*' at front of every line of textarea. I have a hidden textarea which is #repmsg, and assume that in that box have 3 line. I want when user click #modquote, the confirm box will appear, and when user click OK, inside the textarea#modrepmsg will display
>line1
>line2
>line3
Here my jquery code
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var regex = /<br\s*[\/]?>/gi;
var repmsg = comment.replace(regex, "")
var quote = '>' + repmsg;
$('textarea#modrepmsg').val(quote);
}
});
Thanks for helping.
Something like:
$('#modrepmsg').val(function() {
return $('#repmsg').val().split('\n').map(function(line) {
return '>'+line;
}).join('\n');
});
Demo: http://jsfiddle.net/cm7d6/
you could replace \r\n or what ever return / linebreak is in the text area and replace with \r>
then preceed the content with >
You want to use a regex that gets the beginning or a text line so ^ should be used
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var repmsg = comment.replace("/^/g", ">")
$('textarea#modrepmsg').val(repmsg );
}
});

Regex join elements if directly next to each other

I have the following script which allows me to select text, and will then visually highlight it by wrapping the selected text in a span tag.
This normally works fine, but if there is a highlight tag separated from another highlight tag by only a space, it joins the two highlights together.
Javascript
var HVleftPanelContent = $("#highlight-view .top .content");
HVoutputUl = $("#highlight-view .contentBottom ul");
$("p").on("copy", highlight);
function highlight() {
var text = window.getSelection().toString();
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var textStr = selectedText.textContent;
if (textStr == "\n") {
clearSelection();
return false;
} else if (textStr[textStr.length - 1] == "\n") {
textStr = textStr.slice(0, -1);
var reg = new RegExp("\n", "g");
textStr = textStr.replace(reg, "\n<b data='
'></b>") + "\n";
} else if (textStr.indexOf("\n") >= 0) {
var reg = new RegExp("\n", "g");
textStr = textStr.replace(reg, "\n<b data='
'></b>");
}
var span = $("<span class='highlight'>" + textStr + "</span>");
selection.insertNode(span[0]);
if (selectedText.childNodes[1] != undefined) {
$(selectedText.childNodes[1]).remove();
}
var txt = HVleftPanelContent.html();
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
HVoutputUl.html("");
$("#highlight-view .top .content .highlight").each(function () {
$("#highlight-view .contentBottom ul").append("<li><span>" + $(this).html() + "</span></li>");
});
saveIt();
clearSelection();
}
Recap
If HTML looks like this:
This is a short paragraph
And I highlight "is", the markup changes to:
This <span>is</span> a short paragraph
And then I highlight either "this" or "a", the markup erroneously changes to:
This <span>isa</short> paragraph
Instead of how it should change:
This <span>is</span> <span>a</span> paragraph
Potential Problem
I assume the problem lays in this line:
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
Where the Regex statement is joining <span> tags that are next to each other, which it should so that if two span tags are directly next to each other, it becomes one span, but the Regex isn't limiting the joining to only when they're directly next to each other.
So, basically, how can I change the Regex to only join span tags if they're directly next to each other.
Fairly simple, replace:
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
With:
HVleftPanelContent.html(txt.replace(/<\/span><span class="highlight">/g, ''));
The problem was (?:\s)*, which means match any white space 0 or more times, which means that it would match even the spans that are separated with spaces.

Get certain text replace it and wrap it in span?

I have following html<p class="get">This is some content.</p> what I would like to do is to make it like this:<p class="get">This is <span>some</span> content.</p>. To accomplish this I know I should: 1. get my certain text (done that...)
2. Wrap my text in span (done that also...)
3. replace my text with text that contains my span (haven't done it)
My problem is step 3 I just can't figure it out. So how can I replace my "old" text with new one?Thank you guys!!!
Fiddle here
My code looks like this:
$(document).ready(function(){
//get the whole text
var ptext = $(".get").text().split(" ");
var myText = ptext[2];
//alert(ptext[2])
//alert(myText);
if($('.get').text().contains(myText)){
//$('<span>'+myText+'</span>').appendTo($('.get'));
}
else{
alert('no text');
}
});
var word = "some",
regex = new RegExp("\\b" + word + "\\b", "g");
$(".get").html(function(i, html) {
return html.replace(regex, "<span>$&</span>");
});
DEMO: http://jsfiddle.net/V7Wnk/1/
$('.get').html(function (i, v) {
return v.replace('some', '<span>some</span>');
});
$('.get').html($(".get").html().replace("some","<span> some </span>"));

Prototype find class and replace text

I am using the prototype framework [requirement by platform] and I am trying to find a ID and replace some text in the ID so that it disappears.
The HTML looks like:
<div id="top">
login | register
</div>
The problem is I don't want the " | " to appear in the ID "top". So I guess it's sort of "find element " | " in ID top and remove"
Event.observe(window, 'load', function() {
try {
if ($$('#top')!=null) {
var topmenu = document.getElementById('top');
var value = topmenu.value;
// define an array of replacements
var replacements = [
{ from: '|', to: ' ' }
];
for (var i = 0, replacement; i < replacements.length, replacement = replacements[i]; i++) {
// replace
value = value.replace(replacement.from, replacement.to);
}
// replace the old text with the new
topmenu.value = value;
} }
catch(ex) {
}
});
Tried with this above but doesn't work. Can anyone assist ?
Thanks
Can't you just use CSS to hide the pipe? Just change the color to match the background-color so that it is invisible.
#top {color: #fff } /* substitute with the right background color if different */
#top a {color: #000 } /* or whatever it has to be */
EDIT: The right property you should be replacing is innerHTML, not value.
var value = topmenu.innerHTML;
// define an array of replacements
var replacements = [
{ from: '|', to: ' ' }
];
for (var i = 0, replacement; i < replacements.length, replacement = replacements[i]; i++) {
// replace
value = value.replace(replacement.from, replacement.to);
}
// replace the old text with the new
topmenu.innerHTML = value;
Looks like you just need quotes around the |. Otherwise it looks okay. Probably don't need the conditional either since you're in a try catch but maybe that's just too loosy goosy.

Categories

Resources