Replacing html entities with a text using javascript - javascript

Please I want to replace html entities with a text like so: <img src='my_image.jpg'> so I ran this code:
var image = $("#my_div").html($("#my_div").html().replace(/<img scr='(.*?)'>/g, "{{$1}}"));
so when its outputted it show like this: {{my_image.jpg}} but when outputted this is what displays: [object Object]. Please I need help because I know am getting something wrong.

You can change an img element's attribute (src in this case) like this :
Markup:
<img id="eximg" src="source.jpg">
Script:
$('#eximg').attr('src','anothersource.jpg');

You can use a function to create the new value
<img id="myid" src="mypicture.jpg">
<script>
$('#myid').attr('src', function(i, origValue){
return "{{" + origValue + "}}";
});
</script>

Related

txt.replace </blockquote> in textarea js

I give up! I looked at many different answers. I've tried many different ways and nothing works. I want to change the </blackquote> tag to <br /> or a new line in the textarea. Alternatively, change to some other character, because later I can replace another character in PHP to <br/>. How to do it?
Working example for easy understand here: https://jsfiddle.net/jsf88/rb3xp7am/35/
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote><br />
"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐
</div>
</section>
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').text();
//txt = txt.replace('</blockquote>', '<br/>');
//txt = txt.replace(/<\/(blockquote)\>/g, "<br/>");
//txt = txt.replace(/blockquote*/g, '<br/>');
//txt = txt.replace(/(.*?)<\/blockquote>(.*?)/g, ' xxx ');
txt = txt.replace(/<\/blockquote>/gi, '<br/>')//NOT WORKING!!
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');//working great
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
});
To make it funnier, another example with changing the blackquote tag to br works without a problem. Why? can someone explain it?
//OTHER EXAMPLES WHERE CHANGE </BLACKQUOTE> to <br/> WORKING GOOD... WTF?!
string = ` <blockquote>this is a quote for comment😎 </blockquote><br />"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐`;
string = string
.replace(/<\/blockquote>/gi, ' <br /> ');//but here working! ;/
console.log(string);
you recover text with text function ('.replyMsg').text() but in that case you will have the text but with no html tag like <blockquote> so first you will have to recover the html to have the blockquote tag
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
the br tag is not interpreted in textarea so you have to change it by a new line character
don't forget to remove opened bloquote tag to get the expected result
txt = txt.replace(/<blockquote>/gi, '');
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/<\/blockquote>/gi, '\n');
txt = txt.replace(/<blockquote>/gi, '');
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
blockquote {
background-color: silver;
}
.replyMsg {
border: 2px solid green;
}
.quoteMsg {
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote>
"X" -- HERE I want BR_TAG or new line in textare a after c lick 'quote' 😐
</div>
</section>
The first problem in your code was how you were adding the event listener to the ready event. Being it something invented by jQuery, and not a native event, the correct way to do it should be as of now (v.3.3.1 the version I used in this demo) $(document).ready(()=>{/*code here*/}).
As a further reference:
https://api.jquery.com/ready/
There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes
ready before this event is attached, the handler will not be executed.
But... it's not perfectly clear how did you wish to transform your text before setting the value of the textarea. So I just better factored your logic so that you have some clear steps:
grabbing the blockquote element text content and trimming it (being the origin)
applying the transform newline to whitespace (with the regex that I left untouched)
build the final string as a template literal that will include the quote content, the meta tags wrapping it, AND anything else you wish to add like for example a new line (\n) that in this example is exacerbated by a text following it.
There's a hint in your words that put me in the position to say something superflous but still deserving an attempt: the value of a inner text is just plain text and doesn't render html content. So the <br> itself would remain as you read it and wouldn't have any rendering effect on the textarea content. That's why I focused my demonstration on putting a newline with the escaping sequence. It works both on double quoted strings and template literals: "\n" `\n`
Further notes
It seems the original approach of processing the blockquote html was preferred. It's worth saying that it was appearently a terrible strategy for several reasons:
It grabs the blockquote content as html despite that's not how it's
rendered on the page.
It takes the effort to consider the whole outerHTML removing the
wrapping blockquote tags instead of fetching directly the innerHTML.
It adds the newline as newline instead of embedding it as <br> so
at this point I ask myself if the content in the textarea was
supposed to be encoded html or not.. and the added br would then
belong to something meta?
It's harder to deal with in case you want to further customize the
string processing
But... maybe there's something I didn't get and I'm doing weak assumptions.
//since you are using the ready event with jquery, that's the correct syntax
$(document).ready(function() {
$('.quoteMsg').click(function() {
//grabs the text content of the blockquote element (trimming it)
var quoteTextContent = $(this).closest('.replyBox').find('.replyMsg').text().trim();
//performs the transform already in place in your code.. replacing newlines with white spaces
quoteTextContent = quoteTextContent.replace(/(?:\r\n|\r|\n)/g, ' '); //working great
//builds the string to set the textarea value with, using a template literal
//here you can add anything you want.. like a new line but that's just an example
const encoded = `[quote]${quoteTextContent}[/quote]\nand something following to show the new line happening`;
console.log(encoded);
$("textarea[name='quote']").val( encoded );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎
<br>
Having new lines also ... since you perform a regex transform newline=>whitespace
</blockquote><br />
</div>
</section>
Well, thanks for answers. The problem was a missing .html tag.
This script work for me almost perfect for quoting few times:
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/</g, "<");
txt = txt.replace(/>/g, ">");
txt = txt.replace(/&/g, "&");
txt = txt.replace(/"/g, '"');
txt = txt.replace(/'/g, "'");
txt = txt.replace(/<br>/g, "");
txt = txt.replace(/<hr>/g, "[hr]");
//txt = txt.replace(/<hr>/g, "\n");
txt = txt.replace(/<blockquote>/gi, '');
txt = txt.replace(/<\/blockquote>/gi, '[hr]');
txt = txt.replace(/[hr][hr]/gi, "");//not working ([][])
txt = txt.replace(/[hr][hr]/gi, "[hr]");//not working ([[hr]][[hr]])
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]\n'));
});
});
The problem here is I dont know how to change dubble [hr][hr] for nothing, because this txt = txt.replace(/[hr][hr]/g, ""); not working, so would be cool for more explain about. One more time big thanks for answers! this function .replace is not as intuitive as in PHP.
EDIT: ahh.. I think is not possible to delete this dubel, because I extra insert it two times. Nvm. I will find and del this dubel in PHP.

How to add a javascript variable to div?

I have some code that is roughly along the lines of this:
exportValue = [];
function reduceArray() {
//does something
exportValue = parseFloat(exportValue)
}
From that, I get that exportValue is 73951. I then have to add that number to the page... so I tried both of these:
$("#exportValueDiv").append(exportValue);
$("#exportValueDiv").append("<li>" + exportValue + "</li>");
But that doesn't work.. I'm confused on how to add something like a variable to the DOM....
If I do something like:
$( "#exportValueDiv" ).append( "<li>value</li>")
it works, but I don't want to add a string, I want to add the value of the variable. I looked this up, but I'm still confused, so any help would be greatly appreciated!!!
Look into jQuery manipulation
$("#exportValueDiv").text(exportValue); //Replaces text of #exportValueDiv
$("#exportValueDiv").html('<span>'+exportValue+'</span>'); //Replaces inner html of #exportValueDiv
$("#exportValueDiv").append('<span>'+exportValue+'</span>'); //Adds to the inner html of #exportValueDiv
The .append() contract expects a DOM element or HTML String. You will need to do:
$("#exportValueDiv").append("<div>" + exportValue + "</div>");
Try this:
$("#exportValueDiv").append("<div>" + exportValue + "</div>");
The following appends your variable to a div that already has information:
<div id="exportValueDiv">
<p>
Some information.
</p>
</div>
<script>
var exportValue = "Hello world.";
$("#exportValueDiv").append('<p>'+ exportValue +'</p>');
</script>
https://jsfiddle.net/supadave57/f9tqw0d4/

get textarea by class and set name dynamically

I don't really know why I can't do this apparently silly thing.
I have a template that parses dynamically a js file with an html textarea only with the class attribute.
What I want to do is to add name attribute to it so I can get it with $_POST in php.
So far I have tried:
var txt = $('.note-codable');
txt.prop('name','description');
$('.note-codable').attr('name','description');
and other options that doesn't seem to work.
This is html that is added dinamycally:
<div class="note-editor">
//other divs
<textarea class="note-codable"></textarea>
</div>
when I do (in order to TRY the code):
var txt = $('.note-codable');
alert(txt);
the result is [object] [object]
what am I missing? why is attr name not writing?
Try this, tell me if there is anything else I can do.
window.onload = function(){
//get the element
var txt = $('.note-codable');
//set the name attribute
txt.name = 'yourName';
//get the name and console.log it
console.log(txt.name);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="note-editor">
//other divs
<textarea class="note-codable"></textarea>
</div>
You seem to be doing it right... Here's an example for clarity.
$(function() {
var $el = $("#example");
var $out = $("#output");
$out.append("<p>Name is: " + $el.attr('name') + "</p>");
$el.attr('name', 'description');
$out.append("<p>Name is: " + $el.attr('name') + "</p>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="example"></textarea>
<div id="output"></div>
Your code is working on my end: the name is set dynamically. You are getting [object object] from the alert because you are returning the textbox itself, not its contents or the value of its name attribute.
Assuming you want the name put into the textbox instead of added as an attribute, you should set it with txt.val('your name here').
var txt = $('.note-codable');
txt.attr('name', 'description');
console.log(txt.get(0));
txt.val(
'html: ' + txt.parent().html().trim() + '\n' +
'name: ' + txt.attr('name')
);
textarea {
height: 100px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="note-editor">
<textarea class="note-codable"></textarea>
</div>
If you alert an object(like what the jQuery selector will return) it will not give display the information. It will always read [object Object]. Using console.log would be a better way to read through it. Alternatively, if just want to test if the name attribute is in fact applied, this should the trick.
var txt = $('.note-codable').attr('name');
alert(txt);
Assuming the jQuery was successful, it should read description

JQuery onclick attribute undefined in each() loop

Please forgive my awful coding style. I am learning to write a Chrome extension and can't figure out some JQuery stuff. I am trying to parse a document with some rows, each containing a (dynamically generated?) link, the HTML code looks like this:
<div class="row" id="rand">
<div class="display">
<div class="link">
<a name="actionLink" href="#" alt="action" onclick="listener.postAction('form', 'http://***/')" class="alink"><span>Confirm</span></a>
</div>
</div>
I am grabbing the info the following way:
$(".row").each(function(index)
{
var $itemArea = $(this).find(".display");
var id = $(this).attr("id");
var alink = $(this).find(".link").find("a");
var onclick = alink.attr("onclick");
console.log("id=" + id);
console.log("alink=" + alink);
console.log("onclick=" + onclick);
});
Here's the output from JSBin:
"id=rand"
"alink=[object Object]"
"onclick=listener.postAction('form', 'http://***/')"
However, when I debug this in Chrome, the value of "onclick" returned by my code is undefined. To make things more confusing, when I inspect the onclick attribute of alink, it shows the correct value? What am I doing wrong?
Try the following to get your var instead
var onclick = $('.link a:first',this).attr('onclick');

JQuery add textarea inside a div

I'm trying to add textarea dynamically inside a div using JQuery & have following code:
#{
string emailText = ViewBag.email as string;
}
<script type="text/javascript">
$(document).ready(function () {
var textArea = $('<textarea style="padding-left:100px" />');
emailText = emailText.replace("$[Group Custom Text]$", textArea);
$("#divConfirmation").append(emailText);
});
</script>
<div id="divAppointmentConfirmation"></div>
Problem is I get string value "[object Object]" instead of HTML control (textarea).
Yes, because textArea is a jQuery object.
And ({}).toString() is "[object Object]".
Use outerHTML to get its html.
emailText = emailText.replace("$[Group Custom Text]$", textArea[0].outerHTML);
That's because it need a string as parameter. You can try this:
emailText.replace("$[Group Custom Text]$", textArea[0].outerHTML);
check the following sentences:
$("#divConfirmation").append(emailText);
<div id="divAppointmentConfirmation"></div>
you can trivially observed that divConfirmation isn't divAppointmentConfirmation correct it too.

Categories

Resources