Alternate code for "if else" in my code - javascript

Below given was my javaScript code.
Condition is, If I give a word like hello. the image for a hello should be displayed or if I give facebook, the image for that has to be displayed likewise for many words, the mentioned image has to be displayed.. But here in my code condition gets failed after first time and image is not displaying for the second word.
Help me with the alternate code for the above mentioned problem
var anu = document.getElementById("display");
var a= document.getElementById("final_span").textContent;
console.log(linebreak(interim_transcript));
if(a.search("hello") || a.search("facebook")){
if(linebreak(interim_transcript) == "hello"){
anu.innerHTML="<img src=hello.jpg>";
}
else if(linebreak(interim_transcript) == "facebook"){
anu.innerHTML="<img src=facebook.jpg>";
}
else if(linebreak(interim_transcript) == "hi"){
anu.innerHTML="<img src=hi.jpg>";
}
else if(linebreak(interim_transcript) == "doll"){
anu.innerHTML="<img src=doll.jpg>";
}

If the value returned by linebreak and image name are same you can use
anu.innerHTML = '<img src="' + linebreak(interim_transcript) + '">';
Otherwise you can use a object where you can specify the image name
var obj = {
hello: "hello.jpg",
facebook: 'facebook.jpg',
hi: 'hi.jpg'
}
var anu = document.getElementById("display");
var a = document.getElementById("final_span").textContent;
if (a.search("hello") || a.search("facebook")) {
var lb = linebreak(interim_transcript);
if (obj[lb]) {
anu.innerHTML = '<img src="' + obj[lb] + '">';
}
}

Related

Pass 2 Functions Through One OnChange Event - With HREF on both Functions

I have asked something similar in the past but was able to resolve it by separating the functions by events. I need to be able to pass 2 href events in one Onchange Event because it is a dropdown, OR I need to be able to tie the second function into another Event.
This works only when an alert() is inserted. Once I take the alert() out it does not work. I've tried to supress the alert while still keeping it in the code and it works fine. I do not want the alert but I want the results.
HTML Here:
<select id="PartList" class="form-control form-control-lg ml-0" onChange="SelectMain();">
JavaScript Here
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1 HERE='+ "'" + text + "'" ;
//alert(value);
//alert(text);
window.location.href = str;
}
function SelectValue() {
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2 HERE' + value ;
alert(value);
window.location.href = str;
}
function SelectMain() {
sList();
SelectValue();
}
function alert(message) {
console.info(message);
}
This is resolved, for those that come to this question. The problem wasn't with the JavaScript it was because the device I was sending the commands to couldn't handle the commands that fast. I have incorporated the resolved code with troubleshooting techniques.
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1='+ "'" + text + "'" ;
//str1 = 'http://google.com';
//alert(value);
//alert(text);
window.location.href = str;
//window.open(str1);
}
function SelectValue() {
setTimeout(function(){
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2=' + value ;
//str1 = 'http://aol.com';
//alert(value);
window.location.href = str;
//window.open(str1);
},1000);
}

Replace text to image in jquery

This is my jquery script for validating the file extension.
function ValidateExtension() {
var allowedFiles = [".csv", ".xlsx", ".txt"];
var fileUpload = document.getElementById("product_file1");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "Your file has been imported.Please wait few for minutes";
return true;
}
Here! what I am trying to do, The above code is like this:
lblError.innerHTML = "Your file has been imported.Please wait few for minutes";
But I am changing link this,
lblError.innerHTML = '<img src="/assets/spin.gif">';
NOTE:Why? I am editing this code means.When i have to uploading a file the message will be display the text but i want display image only,
This is possible?
Always remember you need to use escape characters while you try to insert an image tag in innerHTML component. Do it like this and it will 100% work .Try this code below
<img src=\`assets/spin.gif\`>
Let me know if that helps :)
Yes, is possible.
Look https://jsfiddle.net/1kzoqg8x/
var lblError = document.getElementById("lblError");
lblError.innerHTML = '<img src="http://media.iterar.co/app-site/images/spinner.gif" />';
This is it you need?

Java Applet is undefined

I have this jzebra applet that I need to do some client side ticket printing.
This is the applets html definition:
<applet id="jzebra" name="jzebra" code="jzebra.PrintApplet.class" archive="../../../../../../web/org.openbravo.howtos/lib/jzebra.jar"
width="10px" height="10px">
The function I call in the form button is this:
function printDocument() {
var applet = document.jzebra;
var frm = document.frmMain;
var url = frm.elements["inpftpOBDir"].value;
var file ="0.txt";
var archivo = url + "/" + file;
if (applet != null) {
var printname = frm.elements["inpPrinterName"].value;
var indice = frm.inpPrinterSelected.selectedIndex;
var printselected = frm.inpPrinterSelected.options[indice].text;
alert(printname);
alert(printselected);
if(printselected == ""){
// printname = "zebra"
//alert('Default : ' + printname);
applet.findPrinter(printname);
monitorFinding();
} else {
//alert('Selected : ' + printselected);
applet.findPrinter(printname);
monitorFinding();
}
alert('File : ' + archivo);
// applet.findPrinter(printname);
applet.appendFile(archivo);
// Send characters/raw commands to printer
applet.print();
alert('The document was sent to the printer.');
}
}
I checked the console and there is a definition of applet, but when it reaches applet.findPrinter(printname), just explodes because applet.findPrinter is not a function.
Has anyone faced this struggle before? I have seen that there is a little gray square in the top left corner of my page. When I hover on it, it displays "undefined".
I finally came up with a very complex solution, having to use jnlp. I will post my code later for references, if anyone else find similar problems.

How to add custom image tag to pagedown?

I'm attempting to duplicate the original img tag's functionality in custom img tag that will be added to the pagedown converter.
e.g I'm copy the original behavior:
![image_url][1] [1]: http://lolink.com gives <img src="http://lolink.com">
into a custom one:
?[image_url][1] [1]: http://lolink.com gives <img class="lol" src="http://lolink.com">
Looking at the docs the only way to do this is through using the preblockgamut hook and then adding another "block level structure." I attempted doing this and got an Uncaught Error: Recursive call to converter.makeHtml
here's the code of me messing around with it:
converter.hooks.chain("preBlockGamut", function (text, dosomething) {
return text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, function (whole, inner) {
return "<img src=" + dosomething(inner) + ">";
});
});
I'm not very experienced with hooks and everything so what would I do to fix it? Thanks.
UPDATE: found out that _DoImages runs after prespangamut, will use that instead of preblockgamut
Figured it out! The solution is very clunky and involves editing the source code because I am very bad at regex and the _DoImage() function uses a lot of internal functions only in the source.
solution:
All edits will be made to the markdown.converter file.
do a ctrl+f for the _DoImage function, you will find that it is named in two places, one in the RunSpanGamut and one defining the function. The solution is simple, copy over the DoImage function and related stuff to a new one in order to mimic the original function and edit it to taste.
next to DoImage function add:
function _DoPotatoImages(text) {
text = text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writePotatoImageTag);
text = text.replace(/(\?\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writePotatoImageTag);
return text;
}
function writePotatoImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
var whole_match = m1;
var alt_text = m2;
var link_id = m3.toLowerCase();
var url = m4;
var title = m7;
if (!title) title = "";
if (url == "") {
if (link_id == "") {
link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
}
url = "#" + link_id;
if (g_urls.get(link_id) != undefined) {
url = g_urls.get(link_id);
if (g_titles.get(link_id) != undefined) {
title = g_titles.get(link_id);
}
}
else {
return whole_match;
}
}
alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()");
url = escapeCharacters(url, "*_");
var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
title = attributeEncode(title);
title = escapeCharacters(title, "*_");
result += " title=\"" + title + "\"";
result += " class=\"p\" />";
return result;
}
if you look at the difference between the new _DoPotatoImages() function and the original _DoImages(), you will notice I edited the regex to have an escaped question mark \? instead of the normal exclamation mark !
Also notice how the writePotatoImageTag calls g_urls and g_titles which are some of the internal functions that are called.
After that, add your text = _DoPotatoImages(text); to runSpanGamut function (MAKE SURE YOU ADD IT BEFORE THE text = _DoAnchors(text); LINE BECAUSE THAT FUNCTION WILL OVERRIDE IMAGE TAGS) and now you should be able to write ?[image desc](url) along with ![image desc](url)
done.
The full line (not only the regex) in Markdown.Converter.js goes like this:
text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
so check the function writeImageTag. There you can see how the regex matching text is replaced with a full img tag.
You can change the almost-last line before its return from
result += " />";
to
result += ' class="lol" />';
Thanks for the edit to the main post.
I see what you mean now.
It is a bit weird how it uses empty capture groups to specify tags, but if it works, it works.
It looks like you would need to add on an extra () onto the regex string, then specify m8 as a new extra variable to be passed into the function, and then specify it as class = m8; like the other variables at the top of the function.
Then where it says var result =, instead of class =\"p\" you would just put class + title=\"" + .......

Regex replace url with links

I need a little help with some regex I have. Basically I have a shout box that only shows text. I would like to replace urls with links and image urls with the image. I've got the basics working, it just when I try to name a link that I have problems, well if there is more than one link... check out the demo.
Named link format {name}:url should become name. The problem I am having is with shout #5 where the regex doesn't split the two urls properly.
HTML
<ul>
<li>Shout #1 and a link to google: http://www.google.com</li>
<li>Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg</li>
<li>Shout #3 with two links: http://www.google.com and http://www.yahoo.com</li>
<li>Shout #4 with named link: {google}:http://www.google.com</li>
<li>Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com</li>
</ul>
Script
var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;
$('ul li').each(function(i){
var shout = $(this);
shout.html(function(i,h){
var p = h.split(rex1),
img = h.match(rex2),
typ = (p[2] !== '') ? '$2' : 'link';
if (img !== null) {
shout.addClass('shoutWithImage')
typ = '<img src="' + img + '" alt="" />';
}
return h.replace(rex1, typ);
});
});
Update: I figured it out thanks to Brad helping me with the regex. In case anyone needs it, here is the updated demo and code (Now works in IE!!):
var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;
$('ul li').each(function(i) {
var shout = $(this);
shout.html(function(i, h) {
var txt, url = h.split(' '),
img = h.match(rex2);
if (img !== null) {
shout.addClass('shoutWithImage');
$.each(img, function(i, image) {
h = h.replace(image, '<img src="' + image + '" alt="" />');
});
} else {
$.each(url, function(i, u) {
if (rex1.test(u)) {
txt = u.split(':')[0] || ' ';
if (txt.indexOf('{') >= 0) {
u = u.replace(txt + ':', '');
txt = txt.replace(/[\{\}]/g, '');
} else {
txt = '';
}
url[i] = '' + ((txt == '') ? 'link' : txt) + '';
}
});
h = url.join(' ');
}
return h;
});
});
(\{(.+?)\}:)
you need the ? to make the regex become "ungreedy" and not just find the next brace.
EDIT
However, if you remove the {yahoo}: the second link becomes null too (seems to populate the anchor tag, just no attribute within). This almost seems to be a victim of using a split instead of a replace. I would almost recommend doing a once-over looking for links first, then go back around looking for images (I don't see any harm in off-linking directly to the image, unless that's not a desired result?)

Categories