I have the following code which is partially what my HTML page does.
<script>
function close() {
MainJavaScript();
}
function MainJavaScript()
{
//var strEntity = " ";
var strEntity = document.getElementById('Entity').value;
//Images setup by Entity
if (strEntity == "MGP")
{
document.getElementById('displayPic').src="http://mgp75.png";
}
else if (strEntity == "MPP")
{
document.getElementById('displayPic').src="http://mpp75.png";
}
else if (strEntity == "RSC")
{
document.getElementById('displayPic').src="http://rsc75.png";
}
else if (strEntity == "MSN")
{
document.getElementById('displayPic').src="http://msn75.png";
}
var strFirstName = "John";
var strLastName = "Doe";
var strSuffix = " ";
var strTitle = "DDS";
var strSecondaryTitle = " ";
var strDisplayName = strFirstName + " " + strLastName;
if (strTitle.trim() != '')
strDisplayName += ", " + strTitle;
if (strSuffix.trim() != '')
strDisplayName += ", " + strSuffix;
if (strSecondaryTitle.trim() !='')
strDisplayName += ", " + strSecondaryTitle;
document.getElementById('FullName').innerHTML = strDisplayName;
}
</script>
Submit
<table>
<tr>
<td width="55%">
<div class="first">
<div class="contact-info">
<h3><img id="displayPic" src="" alt=""></h3>
</div><!--// .contact-info -->
</div>
</td>
<td width="40%">
<div>
<h1><font color="#003893" face="Georgia">Cu Vi</font></h1>
<h2><span id="FullName"></span></h2>
</div>
</td>
</tr>
</table>
When I click the Submit button the displayPic and the FullName is replaced by the respective values using MainJavascript function. What I am looking to do is create a PDF from the output but unfortunately all the DLLs and method I found requires me to output a HTML file and then convert to a PDF but because it is using JavaScript, the source is always blank but the display is changed once the button is clicked.
How can I achieve what I am looking to do, is convert the output into a PDF?
You should look at Xep CloudFormatter. This library, jquery plugin, prints any html page. So, given your example, if I were to start with an HTML template like you have, and then with javascript/jquery I populate the html and then call xepOnline.Formatter.Format to render it, you will get back a beautiful PDF.
I simplified your code a bit, but here is a fiddle for you to explore:
http://jsfiddle.net/kstubs/56x6W/
function printMe() {
tryAtMain();
var imgLoad = imagesLoaded($('#displayPic')[0]);
imgLoad.on( 'always', function() {
xepOnline.Formatter.Format('print_me', {
pageMargin: ".25in"
});
});
}
function tryAtMain() {
// some pic
$('#displayPic').attr('src','http://lorempixel.com/output/abstract-q-c-370-222-1.jpg');
$('#FullName').html('Johnny Carson');
}
Related
I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.
I have the following script that is not giving me the result I want. JSFiddle link at the bottom.
Note: This is not my image. I grabbed it randomly from imgur.
I expect:
<img src="https://i.imgur.com/MiOeWrk.jpg" style="max-width:800px;">
But I get this, I believe, but I'm unable to write this in a code block while debugging, for some reason.
<img src="http://thisismydomain.com/https://i.imgur.com/MiOeWrk.jpg" style="max-width:800px;">
Here's my script. Please advise:
<div>Show Image</div>
<div id="jsdebug">jsdebug</div>
<div id="video_aba">video_aba</div>
<script>
function viewimage(ytlink, uid) {
var imagelink = ytlink;
document.getElementById("jsdebug").innerHTML = imagelink;
var uid = uid;
if (imagelink.length == 0) {
imageembed = "<strong>Sorry, unable to load.</strong>";
} else {
imageembed = "<img src=\"/" + imagelink + "\" style=\"max-width:800px\">";
}
document.getElementById("video_aba").innerHTML = imageembed;
}
</script>
https://jsfiddle.net/gde5630h/
The problem is what your image link coded . It's like this imageembed = "<img src=\"/" + imagelink + "\" style=\"max-width:800px\">";
/ => this will prepend to your current domain url eg.if your domain is localhost it will goes localhost/https://i.imgur.com/MiOeWrk.jpg
So remove / from your image link
Your attribution is not correct. href should be replaced with onclick event.
"href" is not used for javascript events. It is used to link the webpages.
javascript events are onclick, onhover, onmouseenter, etc.
function viewimage(ytlink, uid) {
var imagelink = ytlink;
var uid = uid;
if (imagelink.length == 0) {
imageembed = "<strong>Sorry, unable to load.</strong>";
} else {
imageembed = `<img src="${ytlink}" style="width:800px">`;
}
document.getElementById("video_aba").innerHTML = imageembed;
document.getElementById("jsdebug").innerText = imageembed;
}
a {
color: blue;
text-decoration: underline;
cursor: pointer;
}
<div>Show Image</div>
<div id="jsdebug">jsdebug</div>
<div id="video_aba">video_aba</div>
I'm trying to create a table showing file information for members after uploading. However, for some reasons, the tag causes the layout to be deflected.
When I open the F12 window, my code is as shown below:
The problem lies in the tag and the tag conjoined together.
Now, I just edit it by adding a space marker or a line delimiter:
Immediately, it creates another tag and contains the entire , tag inside. Interface restored, no more errors!
Here is my entire source code:
<table id="files" class="files table table-striped" width="100%"></table>
var isSuccess = true;
if(data['result'][0]['error'] != null)
{
isSuccess = false;
}
var html = ''; // I tried adding the <tbody></tbody> tag here but
// it still needs a space or line break -> not working!
html += '<tr class="template-download';
if(isSuccess == false)
{
html += ' errorText';
}
html += '" ';
if(isSuccess == true)
{
html += 'onClick="return showAdditionalInformation(this);"';
}
html += '>';
if(isSuccess == true)
{
html += data['result'][0]['success_result_html'];
}
else
{
html += data['result'][0]['error_result_html'];
}
html += '</tr>';
function handleUrlUploadSuccess(data)
{
isSuccess = true;
if(data.error != null)
{
isSuccess = false;
}
html = '';
html += '<tr class="template-download';
if(isSuccess == false)
{
html += ' errorText';
}
html += '" onClick="return showAdditionalInformation(this);">'
if(isSuccess == false)
{
// add result html
html += data.error_result_html;
}
else
{
// add result html
html += data.success_result_html;
// keep a copy of the urls globally
fileUrls.push(data.url);
fileDeleteHashes.push(data.delete_hash);
fileShortUrls.push(data.short_url);
}
html += '</tr>';
$('#rowId'+data.rowId).replaceWith(html);
if(data.rowId == urlList.length-1)
{
// show footer
$('#urlUpload .urlFileListingWrapper .processing-button').addClass('hidden');
$('#urlUpload .fileSectionFooterText').removeClass('hidden');
// set additional options
sendAdditionalOptions();
// setup copy link
setupCopyAllLink();
}
}
The start of your loop or javascript should just be the open tag and not the close. At the end of the loop/javascript you should have the close tag. They should be wrapping all of the table row tags being created.
I'd look at using a single string for your row template then use replace to update it
var html = '';
//Template for our row
var row = "<tr class='template-download{{additionalClasses}} {{onClick}}>{{data}}</tr>"
//Dummy Data
var isSuccess = true;
var data = {
result : [{
success_result_html: "<td>Success</td>",
error_result_html: "<td>Fail</td>"
}]
};
//Populate row depending on condition
if(isSuccess)
{
html = row.replace("{{additionalClasses}}","")
.replace("{{onClick}}", "onClick='return showAdditionalInformation(this);'")
.replace("{{data}}", data['result'][0]['success_result_html']);
}
else
{
html = row.replace("{{additionalClasses}}"," errorText")
.replace("{{onClick}}", "")
.replace("{{data}}", data['result'][0]['error_result_html']);
}
//Add the row to the tbody
document.querySelector("#files tbody").innerHTML = html;
<table id="files" class="files table table-striped" width="100%">
<!-- Add tbody here-->
<tbody>
</tbody>
</table>
First, I am not a programmer anymore... It's been years since doing it and even then it was only VBA and old school HTML.
What I would like to do is to show an image on my site in place of another depending on it's "state". For example, the site is http://w2zxl.hevener.com/ , towards the bottom of the page is a script that loads a HAM radio logbook as well as my current status in nearly real time. If I am on the Air, it will show a small image that says "On Air" and then show what frequency I am on and the Mode I am working in. When I am off the air however, that little image just disappears and shows nothing.
What I would like to do is to create a small image to replace the "nothing". In other words, if I am Off Air, I would like to show an "Off Air" image instead of nothing at all.
Is there an If/Then/Else statement that can do this given the code I am providing below?
Code below:
<!-- HRDLOG.net script start --><center>
<div id="hrdlog-oa"> </div>
<div id="hrdlog">www.hrdlog.net</div>
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
<script type="text/javascript" language="javascript">// <![CDATA[
var ohrdlog = new HrdLog('W2ZXL');
setInterval('ohrdlog.LoadOnAir()', 5000);
ohrdlog.LoadLastQso(10);
// ]]></script>
<img src="http://www.hrdlog.net/callplate.aspx?user=W2ZXL" alt="W2ZXL CallPlate" /></center><!-- HRDLOG.net script stop -->
Consider swapping CSS classes to change the background-image instead. This will simplify the javascript and html markup. When you're on air change the class to onair and toggle as needed to offair.
CSS
.onair {
background-image: url("onair.jpg");
}
.offair {
background-image: url("offair.jpg");
}
Html
<div id="hrdlog-oa" class="offair"></div>
Javascript
var statusDiv = document.getElementById("hrdlog-oa");
if (statusDiv.className == "offair") {
statusDiv.className = "onair";
}
else {
statusDiv.className = "offair";
}
Working jsfiddle http://jsfiddle.net/jasenhk/qMAZU/ using background-color instead.
You can not do that with pure HTML and you had 2 way for solving this
If you like markup languages you can use xsl that have if else tag for you
Using Javascript and check if you be on air show on air image and if you not be shows off air
for you the better way is change some javascript code in your site..
you should overwrite ohrdlog.LoadOnAir then you have two way again:
change http://www.hrdlog.net/hrdlog.js source code and rewrite LoadOnAir function
overwrite LoadOnAir function with inserting script tag after load http://www.hrdlog.net/hrdlog.js
i choose number 2 for you because i think you can`t change script that you load it from another domain address... now you should insert this code after this part:
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
and you can found link of offair image in HrdLog.prototype.ShowOffAir function that now, i point it to http://2.bp.blogspot.com/_Dr3YNV7OXvw/TGNNf561yQI/AAAAAAAABIk/-E2MB4jLP_o/s400/Off-Air.jpg:
<script type="text/javascript" language="javascript">
HrdLog.prototype.ShowOffAir = function() {
return '[<img src="https://i.stack.imgur.com/WEr1B.jpg" height="33" width="65" />][2]';
}
HrdLog.prototype.LoadOnAir = function() {
var t = this;
var async = new Async();
async.complete = function(status, statusText, responseText, responseXML, obj) {
if (status == 200) {
txt = '';
var xmldoc = responseXML;
var onairdoc = xmldoc.getElementsByTagName('OnAir');
if (onairdoc.length == 1) {
onair = onairdoc.item(0);
if (onair.getElementsByTagName('oa_QRZ').length > 0) {
txt += '<img src="http://www.hrdlog.net/images/onair.gif" height="33" width="65" /><br/>';
txt += '<font size="+1">' + onair.getElementsByTagName('oa_QRZ')[0].childNodes[0].nodeValue + ' is on air</font><br/>';
txt += '<b>';
txt += FormatNumber(onair.getElementsByTagName('oa_Frequency')[0].childNodes[0].nodeValue) + ' ';
try {
txt += onair.getElementsByTagName('oa_Mode')[0].childNodes[0].nodeValue + '</b><br/>';
txt += onair.getElementsByTagName('oa_Radio')[0].childNodes[0].nodeValue + '<br/><br/>';
} catch (e) { }
//txt += onair.getElementsByTagName('oa_Status')[0].childNodes[0].nodeValue + '<br/>';
}else{
txt += t.ShowOffAir();
}
}else{
txt += t.ShowOffAir();
}
element = document.getElementById('hrdlog-oa');
if (element != null) {
element.innerHTML = txt;
}
} else {
alert('Error\n' + statusText);
}
}
if ((new Date().getTime() - this._lastLoadOnAir.getTime()) > 14500) {
this._lastLoadOnAir = new Date();
async.req(this._host + 'hrdlog.aspx?onair=' + this._qrz, this);
}
}
</script>
I have this form which import transactions of the user. I enhance the form where user can preview the list of transactions they will be importing to their account.
Sample:
The above sample preview is for the QIF file format which I successfully done.
Now I'm trying to preview the OFX file format and I'm having difficulty to arrange it in a table and get the exact value.
Here are my codes:
<input type="file" name="transactions" id="id_transactions">
<div style="display:none;width:335px;" id="preview-box">
<h4 class="thin" class="black">Import Preview</h4>
<table class="simple-table responsive-table footable">
<thead>
<tr>
<th scope="col" width="10%"><small class="black">Date</small></th>
<th scope="col" width="10%"><small class="black">Amount</small></th>
<th scope="col" width="20%"><small class="black">Payee</small></th>
</tr>
</thead>
</table>
<div class="scrollable" style="height:100px">
<table class="simple-table responsive-table footable">
<tbody id="preview-table"></tbody>
</table>
</div><br/>
</div>
<script>
$('#id_transactions').change(function() {
var upload = document.getElementById('id_transactions')
var files = upload.files
if (files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
var extension = upload.value.split('.').pop().toLowerCase()
var lineSplit = e.target.result.split("\n");
var payee = ''
var date
var amount
var content = "";
var content1 = "";
var content2 = "";
if(extension == "qif"){
// for qif preview
}else if(extension == "ofx"){
$('#preview-box').show(500)
for(var i = 1; i < lineSplit.length; i++) {
//I'm stuck here....
}
}
$('#preview-table').html(content);
};
reader.readAsText(files.item(0));
}
});
</script>
sample.ofx
OFXHEADER:100
DATA:OFXSGML
VERSION:103
SECURITY:NONE
ENCODING:USASCII
CHARSET:1252
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<DTSERVER>20071015021529.000[-8:PST]
<LANGUAGE>ENG
<DTACCTUP>19900101000000
<FI>
<ORG>MYBANK
<FID>01234
</FI>
</SONRS>
</SIGNONMSGSRSV1>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>23382938
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<STMTRS>
<CURDEF>USD
<BANKACCTFROM>
<BANKID>987654321
<ACCTID>098-121
<ACCTTYPE>SAVINGS
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>20070101
<DTEND>20071015
<STMTTRN>
<TRNTYPE>CREDIT
<DTPOSTED>20070315
<DTUSER>20070315
<TRNAMT>200.00
<FITID>980315001
<NAME>DEPOSIT
<MEMO>automatic deposit
</STMTTRN>
<STMTTRN>
<TRNTYPE>CREDIT
<DTPOSTED>20070329
<DTUSER>20070329
<TRNAMT>150.00
<FITID>980310001
<NAME>TRANSFER
<MEMO>Transfer from checking
</STMTTRN>
<STMTTRN>
<TRNTYPE>PAYMENT
<DTPOSTED>20070709
<DTUSER>20070709
<TRNAMT>-100.00
<FITID>980309001
<CHECKNUM>1025
<NAME>John Hancock
</STMTTRN>
</BANKTRANLIST>
<LEDGERBAL>
<BALAMT>5250.00
<DTASOF>20071015021529.000[-8:PST]
</LEDGERBAL>
<AVAILBAL>
<BALAMT>5250.00
<DTASOF>20071015021529.000[-8:PST]
</AVAILBAL>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
Anyone who already done this?
UPDATE:
Output:
You know what, this OFX file format looks a lot like an XML in the second part, with an empty line separating the two parts (correct me if I'm wrong, I don't know this format).
Inside the onload event listener, try something like this:
var ofxParts = e.result.split("\r?\n\r?\n"), ofxHeaders, ofxDocument;
ofxHeaders = JSON.parse("{"
+ ofxParts[0].replace(/(\w+) *: *(\w*)/g, "\"$1\": \"$2\"")
.replace(/\r?\n/g, ", ") + "}");
ofxDocument = new DOMParser().parseFromString(ofxParts[1]
.replace(/<(\w+)>(?!\n|\r\n)(.*)/g, "<$1>$2</$1>"));
Now you should have the OFX headers in a useful Javascript object like this:
ofxHeaders = {
"OFXHEADER": "100",
"DATA": "OFXSGML",
"VERSION": "103",
"SECURITY": "NONE",
"ENCODING": "USASCII",
"CHARSET": "1252",
"COMPRESSION": "NONE",
"OLDFILEUID": "NONE",
"NEWFILEUID": "NONE"
};
and you can crawl and select your OFX document with document.evaluate like any other XML.
This should all be available as far as you're using FileReader. Except IE10, which doesn't support document.evaluate. You'll have to create an ActiveXObject and use loadXML if you want to use XPath.
Or you can just use jQuery:
var $ofx = $.parseXML(ofxParts[1].replace(/<(\w+)>(?!\n|\r\n)(.*)/g, "<$1>$2</$1>"));
Edit: You can now create the rows of the table in this kind of way:
var $xfers = $ofx.find("STMTTRN");
content = $xfers.map(function(xf) {
var $xf = $(xf), date = $xf.find("DTPOSTED").text();
return "<tr><td>" + date.substring(4, 6) + "/" + date.substring(6)
+ "/" + date.substring(0, 4) + "<td></td>" + $xf.find("NAME").text()
+ "</td><td>" + $xf.find("TRNAMT").text() + "</td></tr>";
}).join("");