jQuery replacing letters with HTML - javascript

I am pulling some text from a database and I have , and I would like to replace them with <br> don't really know why it's not working any ideas?
JS Code
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(/\+/g, '<br>');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
Text as its coming from the DB:
Ryan open 30/01/1998, ryan added numberOFIteams of NameOFIteams

1st use replace(/\,/g, '<br>')); yours only replace +
(note the g means replace all, you can also make the search case-insensitive pass the "i" parameter ex: /gi)
2nd use $('.MoreInfoText').html() so your <br> are treated as HTML instead of string.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').html($('.MoreInfoText').text().replace(/\,/g, '<br>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="MoreInfoText">11111,22222,33333,44444,55555</span>

It should be .replace(/,/g,"<br>") so all ,s get replaced with <br>. Right now it's replacing + with <br>.
Also to iterate over every element with class MoreInfoText replacing , with <br> modify your code like this:
$('.MoreInfoText').each(function() {
var text = $(this).text().replace(/,/g, '<br>')
$(this).html(text);
});

Try to use the following code:
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(',', ' ');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});

I would recommend avoiding the usage of <br /> for adding line breaks, you may consider using <p> instead.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').each(function() {
var moreArray = $(this).text().split(',');
var $infotext = '';
for(var i = 0; i < moreArray.length; i++){
$infotext += '<p>' + moreArray[i] + '</p>';
}
$(this).empty().html($infotext);
});
});
If paragraphs are not already placed each on a new line, you can add a CSS rule for that. This helps separating the content from the presentation, which is what CSS is for.

Related

Replace selected text inside p tag

I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));

loop elements by data attribute and replace values

I'm trying to loop through all elements that contain a certain data attribute and then replace/remove certain characters.
//replace chars put in by money mask since model is double
$("input[data-input-mask='money']").each(function() {
alert(this.value); // shows: $ 1,000
alert('test$ ,'.replace('$ ', '').replace(',', '')); //shows: test
this.value = this.value.replace('$ ', '').replace(',', '');
alert(this.value); //shows: $ 1,000
});
this.value is still the original value. What might I be doing wrong here?
Use .localeString()
UPDATE
After rereading the OP, I realize the opposite is desired. That's still easy. Instead of using a mask, use localString(). Then it's a matter of not using localestring() when you processing the values.
SNIPPET
$("input[data-input-mask='money']").each(function() {
var cash = parseFloat(this.value);
var green = cash.toLocaleString('en-EN', { style: 'currency', currency: 'USD' });
alert(green);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-input-mask='money' value="623.23">
<input data-input-mask='money' value="20199">
<input data-input-mask='money' value="">
You can loop through each element and replace it like this.
<script>
$(document).ready(function(e) {
//Retrieve all text of amount di;
$.each( $('.amount'), function(){
var unique_id = $(this).text();
//check if any price is match to FREE THEN replace it with NOT FREE
if(unique_id=='FREE'){
$(this).text("NOT FREE");
}
});
});
</script>

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

Javascript to get the div info

I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
​$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});​​​​​​​​
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.

Add mailto: with jQuery?

<table id="here" border="1">
<tr><td>London</td><td>london#us.uk</td><td>aaa</td><td>aaa</td></tr>
<tr><td>Manchester</td><td>manchester#us.uk</td><td>aaa</td><td>aaa</td></tr>
<tr><td>Liverpool</td><td>liverpool#us.uk</td><td>aaa</td><td>aaa</td></tr>
<tr><td>Ipswich</td><td>ipswich#us.uk</td><td>aaa</td><td>aaa</td></tr>
</table>
Is possible add link mailto: for second columns with email addresses with jQuery (not modify HTML)? If yes, how?
http://jsfiddle.net/zwsMD/1/
You could just replace the contents of each second td with an a element with a mailto: href: http://jsfiddle.net/zwsMD/5/.
​$("#here td:nth-child(2)").each(function() {
var email = $(this).text();
// replace contents
$(this).html(
$("<a>").attr("href", "mailto:" + email).text(email)
);
});​​​​​​​​​​​​​​​​​​​​
Assuming it's always the second td of each row, you could iterate over those elements and wrap the contents in an a element:
$("#here td:nth-child(2)").each(function() {
$(this).contents().wrap("<a href='mailto:" + $(this).text() + "'>");
});​
Here's a working example.
You will need to loop around every row, find the cell you want and wrap a link around the content. You can use wrapInner for this.
$("#here tr").each(function() {
var td = $(this).children().eq(1);
var email = "mailto:" + td.text();
td.wrapInner($("<a>").prop("href", email));
});​
Live example
You could do something like this
​$('td:nth-child(2)').each(function(){
var text = $(this).text();
var href = "mailto:"+text;
var $a = $('<a>', { href: href, text: text});
$(this).text('').append($a);
});​​​​​​​​​​​​​​​​​​​​
fiddle here http://jsfiddle.net/zwsMD/6/

Categories

Resources