mailto link with HTML body - html

I have a couple of mailto links in a HTML document.
<a href="mailto:etc...">
Can I insert HTML formatted body in the mailto: part of the href?
Mail me
Note that (2016) in iOS, it is perfectly fine to add <i> and <b> tags for simple italic, bold formatting.

As you can see in RFC 6068, this is not possible at all:
The special <hfname> "body" indicates that the associated <hfvalue>
is the body of the message. The "body" field value is intended to
contain the content for the first text/plain body part of the
message. The "body" pseudo header field is primarily intended for
the generation of short text messages for automatic processing (such
as "subscribe" messages for mailing lists), not for general MIME
bodies.

Whilst it is NOT possible to use HTML to format your email body you can add line breaks as has been previously suggested.
If you are able to use javascript then "encodeURIComponent()" might be of use like below...
var formattedBody = "FirstLine \n Second Line \n Third Line";
var mailToLink = "mailto:x#y.com?body=" + encodeURIComponent(formattedBody);
window.location.href = mailToLink;

No. This is not possible at all.

It's not quite what you want, but it's possible using modern javascript to create an EML file on the client and stream that to the user's file system, which should open a rich email containing HTML in their mail program, such as Outlook:
https://stackoverflow.com/a/27971771/8595398
Here's a jsfiddle of an email containing images and tables: https://jsfiddle.net/seanodotcom/yd1n8Lfh/
HTML
<!-- https://jsfiddle.net/seanodotcom/yd1n8Lfh -->
<textarea id="textbox" style="width: 300px; height: 600px;">
To: User <user#domain.demo>
Subject: Subject
X-Unsent: 1
Content-Type: text/html
<html>
<head>
<style>
body, html, table {
font-family: Calibri, Arial, sans-serif;
}
.pastdue { color: crimson; }
table {
border: 1px solid silver;
padding: 6px;
}
thead {
text-align: center;
font-size: 1.2em;
color: navy;
background-color: silver;
font-weight: bold;
}
tbody td {
text-align: center;
}
</style>
</head>
<body>
<table width=100%>
<tr>
<td><img src="http://www.laurell.com/images/logo/laurell_logo_storefront.jpg" width="200" height="57" alt=""></td>
<td align="right"><h1><span class="pastdue">PAST DUE</span> INVOICE</h1></td>
</tr>
</table>
<table width=100%>
<thead>
<th>Invoice #</th>
<th>Days Overdue</th>
<th>Amount Owed</th>
</thead>
<tbody>
<tr>
<td>OU812</td>
<td>9</td>
<td>$4395.00</td>
</tr>
<tr>
<td>OU812</td>
<td>9</td>
<td>$4395.00</td>
</tr>
<tr>
<td>OU812</td>
<td>9</td>
<td>$4395.00</td>
</tr>
</tbody>
</table>
</body>
</html>
</textarea> <br>
<button id="create">Create file</button><br><br>
<a download="message.eml" id="downloadlink" style="display: none">Download</a>
Javascript
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();

I have used this and it seems to work with outlook, not using html but you can format the text with line breaks at least when the body is added as output.
Email me

Some things are possible, but not all, say for example you want line breaks, instead of using <br />use %0D%0A
Example:
<img src="images/email.png" alt="EMail PDF Brochure" />

It is worth pointing out that on Safari on the iPhone, at least, inserting basic HTML tags such as <b>, <i>, and <img> (which ideally you shouldn't use in other circumstances anymore anyway, preferring CSS) into the body parameter in the mailto: does appear to work - they are honored within the email client. I haven't done exhaustive testing to see if this is supported by other mobile or desktop browser/email client combos. It's also dubious whether this is really standards-compliant. Might be useful if you are building for that platform, though.
As other responses have noted, you should also use encodeURIComponent on the entire body before embedding it in the mailto: link.

Thunderbird supports html-body: mailto:me#me.com?subject=Me&html-body=<b>ME</b>

Whilst it may not be possible within the parameter of the URL, there is a cheeky solution which allows full HTML. The concept is that you have a hidden element on the page (I am using Bootstrap and Jquery in the example below) which is temporarily revealed and the HTML copied (as per here: How to copy text from a div to clipboard). Following that, you redirect the user to the Mail link so in effect all they then have to do is hit Paste within their designated mail program. I've only tested this on Linux/Thunderbird but the paste also works into Gmail web.
<div id="copyEmailText" class="d-none"><p><strong>This is some HTML</strong>. Please hit paste when your email program opens.</p>
function copyDivToClipboard(element) {
var range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand('copy');
window.getSelection().removeAllRanges();// to deselect
}
$('#copyEmail').on('click',function(){
$('#copyEmailText').toggleClass('d-none');
copyDivToClipboard($('#copyEmailText')[0]);
window.location.href = 'mailto:?subject=Email subject text';
$('#copyEmailText').toggleClass('d-none');
})

Anybody can try the following (mailto function only accepts plaintext but here i show how to use HTML innertext properties and how to add an anchor as mailto body params):
//Create as many html elements you need.
const titleElement = document.createElement("DIV");
titleElement.innerHTML = this.shareInformation.title; // Just some string
//Here I create an <a> so I can use href property
const titleLinkElement = document.createElement("a");
titleLinkElement.href = this.shareInformation.link; // This is a url
...
let mail = document.createElement("a");
// Using es6 template literals add the html innerText property and anchor element created to mailto body parameter
mail.href =
`mailto:?subject=${titleElement.innerText}&body=${titleLinkElement}%0D%0A${abstractElement.innerText}`;
mail.click();
// Notice how I use ${titleLinkElement} that is an anchor element, so mailto uses its href and renders the url I needed

Related

In CSS, is it possible to attribute selectors with a certain word? [duplicate]

I am looking for a CSS selector for the following table:
Peter | male | 34
Susanne | female | 12
Is there any selector to match all TDs containing "male"?
If I read the specification correctly, no.
You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.
Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.
:contains() CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors
Using jQuery:
$('td:contains("male")')
You'd have to add a data attribute to the rows called data-gender with a male or female value and use the attribute selector:
HTML:
<td data-gender="male">...</td>
CSS:
td[data-gender="male"] { ... }
There is actually a very conceptual basis for why this hasn't been implemented. It is a combination of basically 3 aspects:
The text content of an element is effectively a child of that element
You cannot target the text content directly
CSS does not allow for ascension with selectors
These 3 together mean that by the time you have the text content you cannot ascend back to the containing element, and you cannot style the present text. This is likely significant as descending only allows for a singular tracking of context and SAX style parsing. Ascending or other selectors involving other axes introduce the need for more complex traversal or similar solutions that would greatly complicate the application of CSS to the DOM.
You could set content as data attribute and then use attribute selectors, as shown here:
/* Select every cell matching the word "male" */
td[data-content="male"] {
color: red;
}
/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
color: blue;
}
/* Select every cell containing "4" */
td[data-content*="4"] {
color: green;
}
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-content="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
You can also use jQuery to easily set the data-content attributes:
$(function(){
$("td").each(function(){
var $this = $(this);
$this.attr("data-content", $this.text());
});
});
As CSS lacks this feature you will have to use JavaScript to style cells by content. For example with XPath's contains:
var elms = document.evaluate( "//td[contains(., 'male')]", node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null )
Then use the result like so:
for ( var i=0 ; i < elms.snapshotLength; i++ ){
elms.snapshotItem(i).style.background = "pink";
}
https://jsfiddle.net/gaby_de_wilde/o7bka7Ls/9/
As of Jan 2021, there IS something that will do just this. :has() ... only one catch: this is not supported in any browser yet
Example: The following selector matches only elements that directly contain an child:
a:has(> img)
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
https://caniuse.com/?search=has
I'm afraid this is not possible, because the content is no attribute nor is it accessible via a pseudo class. The full list of CSS3 selectors can be found in the CSS3 specification.
For those who are looking to do Selenium CSS text selections, this script might be of some use.
The trick is to select the parent of the element that you are looking for, and then search for the child that has the text:
public static IWebElement FindByText(this IWebDriver driver, string text)
{
var list = driver.FindElement(By.CssSelector("#RiskAddressList"));
var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", text), list);
return ((System.Collections.ObjectModel.ReadOnlyCollection<IWebElement>)element)[0];
}
This will return the first element if there is more than one since it's always one element, in my case.
Excellent answers all around, but I think I can add something that worked for me in a practical scenario: exploiting the aria-label attribute for CSS.
For the readers that don't know: aria-label is an attribute that is used in conjunction with other similar attributes to let a screen-reader know what something is, in case someone with a visual impairment is using your website. Many websites add these attributes to elements with images or text in them, as "descriptors".
This makes it highly website-specific, but in case your element contains this, it's fairly simple to select that element using the content of the attribute:
HTML:
<td aria-label="male">Male</td>
<td aria-label="female">Female</td>
CSS:
td[aria-label="male"] {
outline: 1px dotted green;
}
This is technically the same thing as using the data-attribute solution, but this will work for you if you are not the author of the website, plus this is not some out-of-the-way solution that is specifically designed to support this use case; it's fairly common on its own. The one downside of it is that there's really no guarantee that your intended element will have this attribute present.
If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:
for ( td of document.querySelectorAll('td') ) {
console.debug("text:", td, td.innerText)
td.setAttribute('text', td.innerText)
}
for ( td of document.querySelectorAll('td[text="male"]') )
console.debug("male:", td, td.innerText)
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>12</td>
</tr>
</table>
Console output
text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male
Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:
cells = document.querySelectorAll('td');
console.log(cells);
[].forEach.call(cells, function (el) {
if(el.innerText.indexOf("male") !== -1){
//el.click(); click or any other option
console.log(el)
}
});
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-conten="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:
td.male { color: blue; }
td.female { color: pink; }
can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:
<td class="{{person.gender}}">
Just make sure that the content is only one word! Or you could even map to different CSS class names with:
<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">
For completeness, here's the data attribute approach:
<td data-gender="{{person.gender}}">
If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.
This, for example, will click on the first anchor that contains the words "Bad bear":
browser.click("a*=Bad Bear");
#voyager's answer about using data-* attribute (e.g. data-gender="female|male" is the most effective and standards compliant approach as of 2017:
[data-gender='male'] {background-color: #000; color: #ccc;}
Pretty much most goals can be attained as there are some albeit limited selectors oriented around text. The ::first-letter is a pseudo-element that can apply limited styling to the first letter of an element. There is also a ::first-line pseudo-element besides obviously selecting the first line of an element (such as a paragraph) also implies that it is obvious that CSS could be used to extend this existing capability to style specific aspects of a textNode.
Until such advocacy succeeds and is implemented the next best thing I could suggest when applicable is to explode/split words using a space deliminator, output each individual word inside of a span element and then if the word/styling goal is predictable use in combination with :nth selectors:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span>'.$value1.'</span>;
}
Else if not predictable to, again, use voyager's answer about using data-* attribute. An example using PHP:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span data-word="'.$value1.'">'.$value1.'</span>;
}
If you want to apply style to the content you want. Easy trick.
td { border: 1px solid black; }
td:empty { background: lime; }
td:empty::after { content: "male"; }
<table>
<tr>
<td>Peter</td>
<td><!--male--></td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
https://jsfiddle.net/hyda8kqz/
I find the attribute option to be your best bet if you don't want to use javascript or jquery.
E.g to style all table cells with the word ready, In HTML do this:
<td status*="ready">Ready</td>
Then in css:
td[status*="ready"] {
color: red;
}
Doing small Filter Widgets like this:
var searchField = document.querySelector('HOWEVER_YOU_MAY_FIND_IT')
var faqEntries = document.querySelectorAll('WRAPPING_ELEMENT .entry')
searchField.addEventListener('keyup', function (evt) {
var testValue = evt.target.value.toLocaleLowerCase();
var regExp = RegExp(testValue);
faqEntries.forEach(function (entry) {
var text = entry.textContent.toLocaleLowerCase();
entry.classList.remove('show', 'hide');
if (regExp.test(text)) {
entry.classList.add('show')
} else {
entry.classList.add('hide')
}
})
})
The syntax of this question looks like Robot Framework syntax.
In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead.
The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male

CSS selector for elements with certain content (material design icon) [duplicate]

I am looking for a CSS selector for the following table:
Peter | male | 34
Susanne | female | 12
Is there any selector to match all TDs containing "male"?
If I read the specification correctly, no.
You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.
Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.
:contains() CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors
Using jQuery:
$('td:contains("male")')
You'd have to add a data attribute to the rows called data-gender with a male or female value and use the attribute selector:
HTML:
<td data-gender="male">...</td>
CSS:
td[data-gender="male"] { ... }
There is actually a very conceptual basis for why this hasn't been implemented. It is a combination of basically 3 aspects:
The text content of an element is effectively a child of that element
You cannot target the text content directly
CSS does not allow for ascension with selectors
These 3 together mean that by the time you have the text content you cannot ascend back to the containing element, and you cannot style the present text. This is likely significant as descending only allows for a singular tracking of context and SAX style parsing. Ascending or other selectors involving other axes introduce the need for more complex traversal or similar solutions that would greatly complicate the application of CSS to the DOM.
You could set content as data attribute and then use attribute selectors, as shown here:
/* Select every cell matching the word "male" */
td[data-content="male"] {
color: red;
}
/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
color: blue;
}
/* Select every cell containing "4" */
td[data-content*="4"] {
color: green;
}
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-content="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
You can also use jQuery to easily set the data-content attributes:
$(function(){
$("td").each(function(){
var $this = $(this);
$this.attr("data-content", $this.text());
});
});
As CSS lacks this feature you will have to use JavaScript to style cells by content. For example with XPath's contains:
var elms = document.evaluate( "//td[contains(., 'male')]", node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null )
Then use the result like so:
for ( var i=0 ; i < elms.snapshotLength; i++ ){
elms.snapshotItem(i).style.background = "pink";
}
https://jsfiddle.net/gaby_de_wilde/o7bka7Ls/9/
As of Jan 2021, there IS something that will do just this. :has() ... only one catch: this is not supported in any browser yet
Example: The following selector matches only elements that directly contain an child:
a:has(> img)
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
https://caniuse.com/?search=has
I'm afraid this is not possible, because the content is no attribute nor is it accessible via a pseudo class. The full list of CSS3 selectors can be found in the CSS3 specification.
For those who are looking to do Selenium CSS text selections, this script might be of some use.
The trick is to select the parent of the element that you are looking for, and then search for the child that has the text:
public static IWebElement FindByText(this IWebDriver driver, string text)
{
var list = driver.FindElement(By.CssSelector("#RiskAddressList"));
var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('{0}')\"); return x;", text), list);
return ((System.Collections.ObjectModel.ReadOnlyCollection<IWebElement>)element)[0];
}
This will return the first element if there is more than one since it's always one element, in my case.
Excellent answers all around, but I think I can add something that worked for me in a practical scenario: exploiting the aria-label attribute for CSS.
For the readers that don't know: aria-label is an attribute that is used in conjunction with other similar attributes to let a screen-reader know what something is, in case someone with a visual impairment is using your website. Many websites add these attributes to elements with images or text in them, as "descriptors".
This makes it highly website-specific, but in case your element contains this, it's fairly simple to select that element using the content of the attribute:
HTML:
<td aria-label="male">Male</td>
<td aria-label="female">Female</td>
CSS:
td[aria-label="male"] {
outline: 1px dotted green;
}
This is technically the same thing as using the data-attribute solution, but this will work for you if you are not the author of the website, plus this is not some out-of-the-way solution that is specifically designed to support this use case; it's fairly common on its own. The one downside of it is that there's really no guarantee that your intended element will have this attribute present.
If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:
for ( td of document.querySelectorAll('td') ) {
console.debug("text:", td, td.innerText)
td.setAttribute('text', td.innerText)
}
for ( td of document.querySelectorAll('td[text="male"]') )
console.debug("male:", td, td.innerText)
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>12</td>
</tr>
</table>
Console output
text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male
Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:
cells = document.querySelectorAll('td');
console.log(cells);
[].forEach.call(cells, function (el) {
if(el.innerText.indexOf("male") !== -1){
//el.click(); click or any other option
console.log(el)
}
});
<table>
<tr>
<td>Peter</td>
<td>male</td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-conten="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
I agree the data attribute (voyager's answer) is how it should be handled, BUT, CSS rules like:
td.male { color: blue; }
td.female { color: pink; }
can often be much easier to set up, especially with client-side libs like angularjs which could be as simple as:
<td class="{{person.gender}}">
Just make sure that the content is only one word! Or you could even map to different CSS class names with:
<td ng-class="{'masculine': person.isMale(), 'feminine': person.isFemale()}">
For completeness, here's the data attribute approach:
<td data-gender="{{person.gender}}">
If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.
This, for example, will click on the first anchor that contains the words "Bad bear":
browser.click("a*=Bad Bear");
#voyager's answer about using data-* attribute (e.g. data-gender="female|male" is the most effective and standards compliant approach as of 2017:
[data-gender='male'] {background-color: #000; color: #ccc;}
Pretty much most goals can be attained as there are some albeit limited selectors oriented around text. The ::first-letter is a pseudo-element that can apply limited styling to the first letter of an element. There is also a ::first-line pseudo-element besides obviously selecting the first line of an element (such as a paragraph) also implies that it is obvious that CSS could be used to extend this existing capability to style specific aspects of a textNode.
Until such advocacy succeeds and is implemented the next best thing I could suggest when applicable is to explode/split words using a space deliminator, output each individual word inside of a span element and then if the word/styling goal is predictable use in combination with :nth selectors:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span>'.$value1.'</span>;
}
Else if not predictable to, again, use voyager's answer about using data-* attribute. An example using PHP:
$p = explode(' ',$words);
foreach ($p as $key1 => $value1)
{
echo '<span data-word="'.$value1.'">'.$value1.'</span>;
}
If you want to apply style to the content you want. Easy trick.
td { border: 1px solid black; }
td:empty { background: lime; }
td:empty::after { content: "male"; }
<table>
<tr>
<td>Peter</td>
<td><!--male--></td>
<td>34</td>
</tr>
<tr>
<td>Susanne</td>
<td>female</td>
<td>14</td>
</tr>
</table>
https://jsfiddle.net/hyda8kqz/
I find the attribute option to be your best bet if you don't want to use javascript or jquery.
E.g to style all table cells with the word ready, In HTML do this:
<td status*="ready">Ready</td>
Then in css:
td[status*="ready"] {
color: red;
}
Doing small Filter Widgets like this:
var searchField = document.querySelector('HOWEVER_YOU_MAY_FIND_IT')
var faqEntries = document.querySelectorAll('WRAPPING_ELEMENT .entry')
searchField.addEventListener('keyup', function (evt) {
var testValue = evt.target.value.toLocaleLowerCase();
var regExp = RegExp(testValue);
faqEntries.forEach(function (entry) {
var text = entry.textContent.toLocaleLowerCase();
entry.classList.remove('show', 'hide');
if (regExp.test(text)) {
entry.classList.add('show')
} else {
entry.classList.add('hide')
}
})
})
The syntax of this question looks like Robot Framework syntax.
In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead.
The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male

Put an HTML <iframe> into Ext.panel.Panel

I am trying to put an into an ExtJS panel using html config. I have dynamically created which I need to put in this iFrame.
Upon execution, an HTML is getting created under the iFrame but the body appears as empty. no Errors. Following is my ExtJS Panel code
me.outputDataPanel = Ext.create('Ext.panel.Panel', {
bodyStyle : me.htmlBodyStyle,
cls : 'htmlView_font',
border: 0,
style: 'margin: 20px 20px 20px 20px;'
});
On click of a button following happens
me.outputDataPanel.removeAll(true);
var innerHtml = '';
var Id = "SampleID";
var Name = "SampleName";
var DOB = "SampleDOB";
var Gender = "SampleGender";
var patientHeader = '<!DOCTYPE html><html><head><title>My Report</title></head><body>'+
'<table><tr><td style="font-size: 31pt; vertical-align: middle; width: 100%; padding-left:5px;">Report</td></tr></table><br/><br/>'+
'<table class="table_base" style="padding-left:9px;"><tr><td class="report_m1">ID</td><td class="report_m2">'+Id+'</td></tr>'+
'<tr><td class="report_m1">Name</td><td class="report_m2">'+Name+'</td></tr>'+
'<tr><td class="report_m1">Date of Birth</td><td class="report_m2">'+DOB+'</td></tr>'+
'<tr><td class="report_m1">Sex</td><td class="report_m2">'+Gender+'</td></tr></table><br/><br/>'+
'<div id="noteText" style="padding-left:9px;">(Note) This PSD include some errors resulting from differences in the paient\'s actual size and position compared with the model.</div>';
innerHtml+=patientHeader;
innerHtml+='</body></html>';
me.outputDataPanel.add({
bodyStyle: 'overflow-x:hidden; overflow-y:auto',
style: 'border:1px solid #b7bcc4;',
height: "100%",
//html : '<p>test 123</p>'
html: '<iframe id="frameReportPanel" name="frameReportPanelName" style="width:100%; height:100%;" align="middle" isShow="true" name="frame" scrolling="no" frameborder=0 srcdoc="'+innerHtml+'"></iframe>'
});
Didn't understand what exactly is going wrong. Please help!
Have you looked at Ext.ux.IFrame? It's a true Ext JS component, so it may just make your life easier.
IMO, you don't really have to use an iFrame. You could just use a container and to update the html on a container you just have to use the update function. You can look at the documentation here.
However, if you want to load an external web page/remote content, you might want to use loader property of the component/container. You can find the docs here.
You are not correctly escaping the contents of your srcdoc attribute. Since you are quoting it with double quotes, any double quotes in the HTML must be escaped.
innerHtml.replace(/"/g, """)

Cshtml to RTF page break disappears when file opens in Word

thanks in advance for any help you can offer. I have been digging through the various posts here on SO trying to solve a missing page break issue. I have a number of cshtml templates that are rendered using a Razor template engine to produce an RTF file. When the file is opened in Word it completely dumps the html that contains the "break" style used to make a page break. The rest of the template renders exactly as designed. I am thinking that maybe my problem is I'm not rendering out the file correctly in the first place.
Sample .cshtml file starts with:
<div style="width: 100%;" class="newpage">
<p align="center" style="text-align:center">NOTICE</p>
<table>
....middle html content....
</table>
<p class="newpage"></p>
</div>
I've tried putting the page break at the beginning and the end just to see if it made any difference and it didn't.
The razor call that gets the .cshtml file is like this:
newNotice.Body = RazorEngine.Razor.Parse(Notifications.GetTemplate(NotificationTemplate.MyTemplate2), data, NotificationTemplate.MyTemplate2.ToString());
return newNotice;
Then I render out the RTF file in the following code where the style for the page break exists:
protected void ProduceNotification(Notification notice, string title)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + title);
Response.ContentType = "application/rtf";
EnableViewState = false;
var stringWrite = new StringWriter();
var sb = new StringBuilder();
sb.Append(#"<html>
<head>
<title></title>
<style type='text/css'>
.body {
margin: 5em;
background-color: white;
width: 100%;
height: 100%;
font-family: Calibri;
}
.spacing {
line-height: 1.5em;
}
.newpage {
mso-special-character:line-break;
page-break-before:always;
clear: both;
}
</style>
</head><body>");
sb.Append(notice.Body);
sb.Append("</body></html>");
stringWrite.WriteLine(sb);
ClearChildControlState();
Response.Write(stringWrite.ToString());
Response.End();
}
When I open up the file in Word, the page breaks are not being respected so I saved the file to .html to see what the mark up looks like and here's what I see:
In the style definition section it shows the style:
p.newpage, li.newpage, div.newpage
{mso-style-name:break;
mso-style-unhide:no;
mso-margin-top-alt:auto;
margin-right:0in;
mso-margin-bottom-alt:auto;
margin-left:0in;
page-break-before:always;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:"Times New Roman","serif";
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;}
But in the document where the html should show the element with the class on it, it looks like this instead (this is in the middle of the html output):
<div>
<p align=center style='text-align:center'>NOTICE </p>
<table>
......middle html content.....
</table>
</div>
Notice that the style and class are missing from the div tag and the p tag is missing all together. What I can't figure out is, is the conversion to RTF deleting these for some reason or is it the Razor Templating Engine that's stripping out the text? I've also tried changing this to output an .doc format also but the result has been the same.
So the aggravating answer also turned out to be the simplest one. The style was applying to p, li, or div elements but only if the element has some kind of content:
<div class='newpage'> </div>
As long as I used one of the correct elements, it works as long as there is some kind of content (in this case just a space). Once I had it working, I also had to address the issue of it adding an extra blank page to the output since originally I had the line in the cshtml file itself. Instead I moved it to the code behind.
I created a var to hold the last list item, as demonstrated in this SO post here.
var lastItem = myList.Last();
foreach(var d in myList)
{
newNotice.Body += RazorEngine.Razor.Parse(Notifications.GetTemplate(NotificationTemplate.MyTemplate2), data, NotificationTemplate.MyTemplate2.ToString());
if(!ReferenceEquals(d, lastItem))
newNotice.Body += "<div class='newpage'> </div>";
}

Ideas for multicolored textbox?

In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.