Using jQuery to find <em> tags and adding content within them - html

The users on my review type of platform highlight titles (of movies, books etc) in <em class="title"> tags. So for example, it could be:
<em class="title">Pacific Rim</em>
Using jQuery, I want to grab the content within this em class and add it inside a hyperlink. To clarify, with jQuery, I want to get this result:
<em class="title">Pacific Rim</em>
How can I do this?

Try this:
var ems = document.querySelectorAll("em.title");
for (var i = 0; i < ems.length; ++i) {
if (ems[i].querySelector("a") === null) {
var em = ems[i],
text = jQuery(em).text();
var before = text[0] == " ";
var after = text[text.length-1] == " ";
text = text.trim();
while (em.nextSibling && em.nextSibling.className && em.nextSibling.className.indexOf("title") != -1) {
var tmp = em;
em = em.nextSibling;
tmp.parentNode.removeChild(tmp);
text += jQuery(em).text().trim();
++i;
}
var link = text.replace(/[^a-z \-\d']+/gi, "").replace(/\s+/g, "+");
var innerHTML = "<a target=\"_blank\" href=\"http://domain.com/?=" + link + "\">" + text + "</a>";
innerHTML = before ? " " + innerHTML: innerHTML;
innerHTML = after ? innerHTML + " " : innerHTML;
ems[i].innerHTML = innerHTML;
}
}
Here's a fiddle
Update: http://jsfiddle.net/1t5efadk/14/
Final: http://jsfiddle.net/186hwg04/8/

$("em.title").each(function() {
var content = $(this).text();
var parameter_string = content.replace(/ /g, "+").trim();
parameter_string = encodeURIComponent(parameter_string);
var new_content = '' + content + '';
$(this).html(new_content);
});
If you want to remove any kind of punctuation, refer to this other question.

$('em.title').html(function(i,html) {
return $('<a/>',{href:'http://domain.com/?='+html.trim().replace(/\s/g,'+'),text:html});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<em class="title">Pacific Rim</em>
UPDATE 1
The following updated version will perform the following:
Grab the contents of the em element
Combine with the contents of the next element, if em and remove that element
Create a query string parameter from this with the following properties
Remove the characters ,.&
Remove html
Append the query parameter to a predetermined URL and wrap the unmodified contents in an e element with the new URL.
DEMO
$('em.title:not(:has(a))').html(function() {
$(this).append( $(this).next('em').html() ).next('em').remove();
var text = $(this).text().trim().replace(/[\.,&]/g,'');
return $('<a/>',{href:'http://domain.com/?par='+encodeURIComponent(text),html:$(this).html()});
});
Or DEMO
$('em.title:not(:has(a))').html(function() {
$(this).append( $(this).next('em').html() ).next('em').remove();
var text = $(this).text().trim().replace(/[\.,&]/g,'').replace(/\s/g,'+');
return $('<a/>',{href:'http://domain.com/?par='+text,html:$(this).html()});
});
UPDATE 2
Per the comments, the above versions have two issues:
Merge two elements that may be separated by a text node.
Process an em element that's wrapped in an a element.
The following version resolves those two issues:
DEMO
$('em.title:not(:has(a))').filter(function() {
return !$(this).parent().is('a');
}).html(function() {
var nextNode = this.nextSibling;
nextNode && nextNode.nodeType != 3 &&
$(this).append( $(this).next('em').html() ).next('em').remove();
var text = $(this).text().trim().replace(/[\.,&]/g,'').replace(/\s/g,'+');
return $('<a/>',{href:'http://domain.com/?par='+text,html:$(this).html()});
});

Actually,if you just want to add a click event on em.title,I suggest you use like this:
$("em.title").click(function(){
q = $(this).text()
window.location.href = "http://www.domain.com/?="+q.replace(/ /g,"+")
}
you will use less html code on browser and this seems simply.
In addition you may need to add some css on em.title,like:
em.title{
cursor:pointer;
}

Something like this?
$(document).ready(function(){
var link = $('em').text(); //or $('em.title') if you want
var link2 = link.replace(/\s/g,"+");
$('em').html('' + link + '');
});
Ofcourse you can replace the document ready with any type of handler

$('.title').each(function() {
var $this = $(this),
text = $this.text(),
textEnc = encodeURIComponent(text);
$this.empty().html('' + text + '');
});
DEMO

Related

how can i change the html code in crm form?

I used dynamics CRM 2015 and i want to change the OptionSet type to checkboxs.
Just like this:
enter image description here
My solution is use JQuery get the td tag in crm form,and use html() change the td html code.
Like this $("#ubg_note_d").html().But question comes that i can't get the td tag which i want to display the checkbox.Only after i used the browser DEVELOPER TOOLS and select the element,then i can get the tag......i have blocked by this for 1 day,any helps?;)
note:i tried the js and jquery,both can't get the td tag.My code is run in the form Onload event,and i tried the filed Onchange event,trouble still there...
Thing you are trying to achieve is unsupported. Instead you can achieve the same using supported way by creating html web resource, which can be added on form on later.
Code for web resource is as below.
<html><head>
<title></title>
<script type="text/javascript" src="new_jquery_1.10.2.js"></script>
<script type="text/javascript">
// function will be called when web resource is loaded on Form.
$(document).ready(function () {
ConvertDropDownToCheckBoxList();
});
//Coverts option list to checkbox list.
function ConvertDropDownToCheckBoxList() {
var dropdownOptions = parent.Xrm.Page.getAttribute("new_makeyear").getOptions();
var selectedValue = parent.Xrm.Page.getAttribute("new_selectedyears").getValue();
$(dropdownOptions).each(function (i, e) {
var rText = $(this)[0].text;
var rvalue = $(this)[0].value;
var isChecked = false;
if (rText != '') {
if (selectedValue != null && selectedValue.indexOf(rvalue) != -1)
isChecked = true;
var checkbox = "< input type='checkbox' name='r' / >" + rText + ""
$(checkbox)
.attr("value", rvalue)
.attr("checked", isChecked)
.attr("id", "id" + rvalue)
.click(function () {
//To Set Picklist Select Values
var selectedOption = parent.Xrm.Page.getAttribute("new_selectedyears").getValue();
if (this.checked) {
if (selectedOption == null)
selectedOption = rvalue;
else
selectedOption = selectedOption + "," + rvalue
}
else {
var tempSelected = rvalue + ",";
if (selectedOption.indexOf(tempSelected) != -1)
selectedOption = selectedOption.replace(tempSelected, "");
else
selectedOption = selectedOption.replace(rvalue, "");
}
parent.Xrm.Page.getAttribute("new_selectedyears").setValue(selectedOption);
//To Set Picklist Select Text
var selectedYear = parent.Xrm.Page.getAttribute("new_selectedyeartext").getValue();
if (this.checked) {
if (selectedYear == null)
selectedYear = rText;
else
selectedYear = selectedYear + "," + rText
}
else {
var tempSelectedtext = rText + ",";
if (selectedYear.indexOf(tempSelectedtext) != -1)
selectedYear = selectedYear.replace(tempSelectedtext, "");
else
selectedYear = selectedYear.replace(rText, "");
}
parent.Xrm.Page.getAttribute("new_selectedyeartext").setValue(selectedYear);
})
.appendTo(checkboxList);
}
});
}
</script>
<meta charset="utf-8">
</head><body>
<div id="checkboxList">
</div>
</body></html>
Refer below given link for
enter link description here
No code needed for that. It's just configuration on CRM to change the display format : checkbox.

Javascript ReGEX for JSON

This is all so confusing, I've seen so many examples of how to do different things and cannot seem to find a valid example for what I am trying to do.
I'm using the YQL for the stock quotes only to get just the major indexes, DOW S&P 500 and NASDAQ.
The project is getting the data and working, but I need to determine if the stock value is returning + or - (up or down).
if the market is up or flat, I want to add a CSS class to set it to green, if it is down, I want to set a CSS to red.
One other issue, this only seems to work when I place the function between the head and body, not in the head, not in the body.
<script type="text/javascript">
function stock_quotes(obj)
{
var items = obj.query.results.quote;
var output = '';
var num_quotes = items.length;
items[0].symbol = "DOW ";
items[1].symbol = "NASDAQ ";
items[2].symbol = "S&P 500 ";
//var posquote = {"\d\.?\d{0,9}\.\d{0,9}\s\+"};
//var negquote = {"\d\.?\d{0,9}\.\d{0,9}\s\-"};
for (var i = 0; i < num_quotes; i++) {
var link = items[i].url;
var symbl = items[i].symbol;
var Change_PercentChange = items[i].Change_PercentChange;
var LastTradePriceOnly = items[i].LastTradePriceOnly;
output += "<table><tr><td>" + "<a href='" + link + "'>" + symbl + "</a>" + LastTradePriceOnly + " " + Change_PercentChange + "</td></tr></table>";
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
This is the HTML with the query
<div id='results'></div>
<script type="text/javascript" src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22DOW%22%2C%22%5EIXIC%22%2C%22%5EGSPC%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=stock_quotes'></script>
Ideally I'd like to predefine the html elements which would make it easier to set the css class but one headache at a time.
In the end, this seemed to work just fine
var match_nas_neg = nas_result.match(/\-/);

How to match with RegExp outside of HTML Tags [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
RegEx match open tags except XHTML self-contained tags
How can I match some alphanumerical words that are outside of an HTML Tag instead of match every words
Example:
<div id="mariano mariano mariano" nota="mariano/mariano">mariano was looking forward Mariano. I want to match this "Mariano" too. Mariano</div>
In this example I want to match all "Mariano" outside of the tag id.
I think the key of this issue is looking forward for a "<" before a ">" and match that word, but if the regex find ">" before a "<" this means that the word is in the tag,
But I couldn't manage to achieve/produce a Regex for this.
I fail trying to concat this Regex (?<=^|>)[^><]+?(?=<|$) with another one.
And my final lowest quality solution was:
<!-- language: lang-js -->
var searchFor = new RegExp("((!?<=^|>)" + termino + ")","ig");
var searchFor2 = new RegExp("(" + termino + "(?=<|$))","ig");
var searchFor3 = new RegExp("(!?<=^|[\\s\\.;,])" + termino + "(?=[\\s\\.;,]|$)","ig");
but those 3 don't cover all the alternatives.
Edit: Im working with javascript:
<script>
container.find("p, span, div, .texto,").each(function() {
var containerText = $(this).html();
for (var i = 0; i < terms.length; i++) {
var termino = terms[i];
// 1st issue ">termino" was remplaced for: ">Pedro"
var searchFor = new RegExp("((!?<=^|>)" + termino + ")","ig");
containerText = containerText.replace(searchFor,">Pedroedro");
// 2nd issue "termino<" was remplaced for: "Pedro"
var searchFor2 = new RegExp("(" + termino + "(?=<|$))","ig");
containerText = containerText.replace(searchFor2,"Pedro");
// 3rd issue "[\.\s,;:]termino[\.\s,;:]
var searchFor3 = new RegExp("(!?<=^|[\\s\\.;,])" + termino + "(?=[\\s \\.;,]|$)","ig");
containerText = containerText.replace(searchFor3," Pedro");
};
$(this).html(containerText);
});
</script>
A few things -
Welcome to stackoverflow!
Please, search for questions before asking. There are numerous results for parsing
xml with regex.
Don't use regex expressions for parsing xml/html! Try xpath!
var termino = // how ever you were defining before...
// Give me all divs, where the text content contains value of "termino"
var iterator = document.evaluate('//div/text()[contains(.,' + termino + ')]', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );
try {
// init thisNode to the first item in the iterator
var thisNode = iterator.iterateNext();
// go through all items, alert their content (which should contain termino)
while (thisNode) {
alert( thisNode.textContent );
thisNode = iterator.iterateNext();
}
}
catch (e) {
dump( 'Error: Document tree modified during iteration ' + e );
}

How to add url parameter to the current url?

Currently I'm at
http://example.com/topic.php?id=14
and I want to make a link to
http://example.com/topic.php?id=14&like=like
by not defining the current url. Like Like. However this last one shows me http://example.com/&like=like
There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.
You have to:
topic.php?id=14&like=like
function currentUrl() {
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
return $protocol . '://' . $host . $script . '?' . $params;
}
Then add your value with something like;
echo currentUrl().'&value=myVal';
I know I'm late to the game, but you can just do ?id=14&like=like by using http build query as follows:
http_build_query(array_merge($_GET, array("like"=>"like")))
Whatever GET parameters you had will still be there and if like was a parameter before it will be overwritten, otherwise it will be included at the end.
In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:
<script>
function addUrlParameter(name, value) {
var searchParams = new URLSearchParams(window.location.search)
searchParams.set(name, value)
window.location.search = searchParams.toString()
}
</script>
<body>
...
<a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>
If you wish to use "like" as a parameter your link needs to be:
Like
More likely though is that you want:
Like
It is not elegant but possible to do it as one-liner <a> element
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
Maybe you can write a function as follows:
var addParams = function(key, val, url) {
var arr = url.split('?');
if(arr.length == 1) {
return url + '?' + key + '=' + val;
}
else if(arr.length == 2) {
var params = arr[1].split('&');
var p = {};
var a = [];
var strarr = [];
$.each(params, function(index, element) {
a = element.split('=');
p[a[0]] = a[1];
})
p[key] = val;
for(var o in p) {
strarr.push(o + '=' + p[o]);
}
var str = strarr.join('&');
return(arr[0] + '?' + str);
}
}

Insert a Link Using CSS

I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:
<table><tr><td class="case">123456</td></tr></table>
I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).
So I'd like that "123456" to be changed to a link of this form:
123456
Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..
function makeCasesClickable(){
var cells = document.getElementsByTagName('td')
for (var i = 0, cell; cell = cells[i]; i++){
if (cell.className != 'case') continue
var caseId = cell.innerHTML
cell.innerHTML = ''
var link = document.createElement('a')
link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
link.appendChild(document.createTextNode(caseId))
cell.appendChild(link)
}
}
You can apply it with something like onload = makeCasesClickable, or simply include it right at the end of the page.
here is a jQuery solution specific to your HTML posted:
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('');
});
in essence, over each .case element, will grab the contents of the element, and throw them into a link wrapped around it.
Not possible with CSS, plus that's not what CSS is for any way. Client-side Javascript or Server-side (insert language of choice) is the way to go.
I don't think it's possible with CSS. CSS is only supposed to affect the looks and layout of your content.
This seems like a job for a PHP script (or some other language). You didn't give enough information for me to know the best way to do it, but maybe something like this:
function case_link($id) {
return '' . $id . '';
}
Then later in your document:
<table><tr><td class="case"><?php echo case_link('123456'); ?></td></tr></table>
And if you want an .html file, just run the script from the command line and redirect the output to an .html file.
You could have something like this (using Javascript). Inside <head>, have
<script type="text/javascript" language="javascript">
function getElementsByClass (className) {
var all = document.all ? document.all :
document.getElementsByTagName('*');
var elements = new Array();
for (var i = 0; i < all.length; i++)
if (all[i].className == className)
elements[elements.length] = all[i];
return elements;
}
function makeLinks(className, url) {
nodes = getElementsByClass(className);
for(var i = 0; i < nodes.length; i++) {
node = nodes[i];
text = node.innerHTML
node.innerHTML = '' + text + '';
}
}
</script>
And then at the end of <body>
<script type="text/javascript" language="javascript">
makeLinks("case", "http://bugs.example.com/fogbugz/default.php?");
</script>
I've tested it, and it works fine.
I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:
Here's a php function called 'linker();'that enables a fake CSS attribute
connect: 'url.com';
for an #id defined item.
just let the php call this on every item of HTML you deem link worthy.
the inputs are the .css file as a string, using:
$style_cont = file_get_contents($style_path);
and the #id of the corresponding item. Heres the whole thing:
function linker($style_cont, $id_html){
if (strpos($style_cont,'connect:') !== false) {
$url;
$id_final;
$id_outer = '#'.$id_html;
$id_loc = strpos($style_cont,$id_outer);
$connect_loc = strpos($style_cont,'connect:', $id_loc);
$next_single_quote = stripos($style_cont,"'", $connect_loc);
$next_double_quote = stripos($style_cont,'"', $connect_loc);
if($connect_loc < $next_single_quote)
{
$link_start = $next_single_quote +1;
$last_single_quote = stripos($style_cont, "'", $link_start);
$link_end = $last_single_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size);
}
else
{
$link_start = $next_double_quote +1;
$last_double_quote = stripos($style_cont, '"', $link_start);
$link_end = $last_double_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size); //link!
}
$connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1;
$id_start = strrpos($style_cont, '#', $connect_loc_rev);
$id_end = strpos($style_cont,'{', $id_start);
$id_size = $id_end - $id_start;
$id_raw = substr($style_cont, $id_start, $id_size);
$id_clean = rtrim($id_raw); //id!
if (strpos($url,'http://') !== false)
{
$url_clean = $url;
}
else
{
$url_clean = 'http://'.$url;
};
if($id_clean[0] == '#')
{
$id_final = $id_clean;
if($id_outer == $id_final)
{
echo '<a href="';
echo $url_clean;
echo '" target="_blank">';
};
};
};
};
this could probably be improved/shortened using commands like .wrap() or getelementbyID()
because it only generates the <a href='blah'> portion, but seeing as </a> disappears anyway without a opening clause it still works if you just add them everywhere :D