Manipulate var in jquery by doing find and text - javascript

I use a WYSIWYG editor in my page. I collect the HTML in a callback function. I would like now change the content with jQuery. For that I do a find() to select the text I want to replace. Then I want to replace it, but I'm stuck!
$('.save').click(function() {
var html = $('#edit').editor('get_html');
console.log(html)
var ma_societe_OLD = $(html).find('.ma_societe').attr('data');
var ma_societe = $(html).find('.ma_societe').text();
if (ma_societe === ma_societe_OLD) {
$(html).find('.ma_societe').text('dfdsfsdfds');
}
console.log(html);
});
As you can see, I want to replace the content of the span with my own text. But it's not working.

The issue is because you're making amendments to the jQuery object, but you never store those changes anywhere. You either create a new jQuery object containing the original, unchanged html, or return the html string directly.
Instead, create $(html) in a variable, make your changes to it, then work with it as needed. Something like this:
$('.save').click(function() {
var html = $('#edit').editor('get_html');
var $html = $(html);
var $maSociete = $html.find('.ma_societe')
if ($maSociete.text() === $maSociete.attr('data')) {
$maSociete.text('dfdsfsdfds');
}
var result = $html[0].outerHTML
console.log(result);
});

Related

Dynamically add new element and change its content

I want to "copy" a certain elements and the change some of the text inside them with a regex.
So far so good: (/w working fiddle - http://jsfiddle.net/8ohzayyt/25/)
$(document).ready(function () {
var divs = $('div');
var patt = /^\d\./;
var match = null;
for (i = 0; i < divs.length; i++) {
match = ($(divs[i]).text().match(patt));
$(divs[i]).text($(divs[i]).text().replace(match[0], "5."));
}
});
HTML
<div>1. peppers</div>
<div>2. eggs</div>
<div>3. pizza</div>
This works exactly the way I want it, but I want to add some of the content dynamically, but when I try to change the content of the copied divs, nothing happens.
Please refer to this fiddle:
http://jsfiddle.net/8ohzayyt/24/
I have put some comments, to be more clear what I want to achieve.
I thing that your problem is that you're not passing an element to your changeLabel function, but just a string.
Look at this solution: http://jsfiddle.net/8ohzayyt/26/
Here is the line I changed to make your code work:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
I just wrapped your HTML in $(). this creates an element from the string.
try:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
EDIT:
Brief explanation What I've done.
In order to make $(el).find('div'); work changeLabel() needs an element. Instead of passing newContent as a string doing the above will make it pass as an element which will make $(el).find('div'); work.

jQuery remove certain tags from a string

I have a string where I want to remove all figure tags. I have tried the following:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var result = $(s).find('figure').remove();
The reason this does not work is that find does not find the figure elements because they have children. Does anyone know how I can remove all figure nodes (and everything inside them) and leave the rest of the html in tact?
Note the html is not in the DOM I need to do this via string manipulation. I don't want to touch the DOM.
You can wrap your string in a jQuery object and do some sort of a manipulation like this:
var removeElements = function(text, selector) {
var wrapped = $("<div>" + text + "</div>");
wrapped.find(selector).remove();
return wrapped.html();
}
USAGE
var removedString = removeElements('<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>','figure');
The beauty of this approach is that you can specify a jquery selector which to remove.
Another approach for keeping html and body tag:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var $s = s.replace(/<figure>(.*)<\/figure>/g, "");
console.log($s)

Creating a HTML DOM select element in Javascript and having an onchange event

I am creating HTML DOM elements using Javascript (yes, I know it's nasty).
I can get the select element created but I cannot add an onchange property.
Example:
var sel = document.createElement('select');
sel.id = 'someID';
sel.title = 'Some title';
sel.style.fontWeight = 'bold';
sel.size = 1;
Once I have added the options and have done a
document.getElementById('someOtherID').appendChild(sel);
I get my select element.
What I want to do is, at A above, add:
sel.onChange = 'someJavascriptFunction()';
but it doesn't like it.
Should I be thinking outside of the square? Which one?
The event name should be lowercase, and you need to assign a function instead of a string.
sel.onchange = someJavascriptFunction;
If there's more work to do, you can assign an anonymous function.
// v----assign this function
sel.onchange = function() {
// do some work
someJavascriptFunction(); // invoke this function
};
You should be doing something like this:
sel.onChange = someJavascriptFunction;
(notice that there are no parens after someJavascriptFunction. This means you are attaching the function, not the invocation of the function.
If there's a chance you'll be binding multiple functions to that event, you will want to use this slightly more lengthy method.
if (sel.addEventListener) {
sel.addEventListener('change', changeFunction, false);
} else if (sel.attachEvent) {
sel.attachEvent('onchange', changeFunction);
} else {
sel.onchange = changeFunction;
}
An easier way to do the whole thing is: somewhere already in your page:
<div id=someContainer></div>
then in your javascript do this:
document.getElementById('someContainer').innerHTML = "<select id=someId title='some title' size=1 style='font-weight: bold' onchange='someJavascriptFunction()' >";
or more slowly:
var html = "<select id=someId title='some title' size=1 style='font-weight: bold' onchange='someJavascriptFunction()' >";
var someContainer = document.getElementById('someContainer');
someContainer.innerHTML = html;
The document.getElementById() is so common, you might have a library like jquery or prototype that does that more easily like $('someContainer'), or else define it for yourself (var $ = document.getElementById;).
innerHTML is a pseudo-variable on every dom element that returns, or sets, all the html INSIDE the element you do it on. You can pass it arbitrarily long HTML, the whole page I guess if you want. and you can write a crafty program to build the html text, they even have templating systems like hogan (google it).

How to remove duplicated content/value with jQuery

So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...
This is how looks like my output html:
<span class="some_class">
"value01"
"value01"
"value02"
"value03"
"value03"
</span>
I can't add any function because i have no idea how to do this, can u help me?
If these values are being added by JS code, then You can make sth like this:
http://jsfiddle.net/Sahadar/Nzs52/5/
You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.
function(event) {
var textareaValue = textarea.value();
if(insertedTexts[textareaValue]) {
event.preventDefault();
textarea.value('');
} else {
insertedTexts[textareaValue] = true;
someSpan.append("\""+textareaValue+"\"");
}
}
If these values are already inside span, use function as follows:
var someSpan = $('.some_class');
var insertedTexts = [];
var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
return value.substring(1,value.length);
});
result.forEach(function(value) {
if(insertedTexts.indexOf(value) === -1) {
insertedTexts.push(value);
}
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);
It's rebuilding span text (trimming etc.) but main functinality is preserved.
jsFiddle working copy:
http://jsfiddle.net/Sahadar/kKNXG/6/
Create an array variable
var vals = [];
which keeps track of the items. Then, in your function that appends items to the span check:
if (vals.indexOf("Mynewvalue") > -1) {
// Add to the span...
}

Replace text with HTML element

How can I replace a specific text with HTML objects?
example:
var text = "some text to replace here.... text text text";
var element = $('<img src="image">').event().something...
function ReplaceWithObject(textSource, textToReplace, objectToReplace);
So I want to get this:
"some text to replace < img src...etc >.... text text text"
And I would like manipulate the object element without call again $() method.
UPDATE:
I solved.
thanx #kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace.
This is the script:
$(document).ready(function() {
var text = "some text to replace here.... text text text";
var element = $('<img />');
text = text.split('here');
$('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
$(element).width(100);
});
I didnt know that append method accept multiples elements.
That is the idea, only need to automate for multiple replacements
thanx to all, and here the jsfiddle
do a split on the text you want to replace then use the array indexes 0 and 1...something like:
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
var strings = textSource.split(textToReplace);
if(strings.length >= 2) {
return strings[0] + objectToReplace.outerHTML() + strings[1];
}
return "";
}
UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.
I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.
You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
return textSource.replace(textToReplace, objectToReplace.outerHTML());
}
function textToObj (text,obj,$src){
var className = "placeholder-"+text;
$src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
$("."+className).replace(obj);
}
you can use $(selector).outerHtml to get the html string of an element
You can replace the html directly: http://jsfiddle.net/rkw79/qNFKF/
$(selector).html(function(i,o) {
return o.replace('old_html','new_html');
})

Categories

Resources