Pass JavaScript Function in href - javascript

I am working on VS2103 Cordova App. I have created list of items. I want to pass data to another page when i press on item. I've created this list by jQuery.
Here is my code :
for (var i = 0; i < data.length; i++) {
if ((Provider == "Doctors")) {
$("#list").append('<li class="list-message" ><a class="w-clearfix w-inline-block" href="javascript:ProviderDetails(' + data[i].DoctorName + ',' + data[i].DoctorAddress + ',' + data[i].DoctorPhone + ',' + data[i].DoctorPhone2 + ',' + data[i].DoctorPhone3 + ',' + data[i].DocLat + ',' + data[i].DocLong + ',' + data[i].DoctorNotes + ',' + data[i].Category + ');" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/Doctors.png"></div></div><div class="column-right"><div class="message-title">' + data[i].DoctorName + '</div><div class="message-text">' + data[i].DoctorAddress + '</div></div></a></li>');
}
}
And here is my function :
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category) {
localStorage.setItem("Name", Name);
localStorage.setItem("Address", Address);
localStorage.setItem("Tel", Tel);
localStorage.setItem("Phone2", Phone2);
localStorage.setItem("Phone3", Phone3);
localStorage.setItem("Lat", Lat);
localStorage.setItem("Lang", Lang);
localStorage.setItem("Notes", Notes);
localStorage.setItem("Category", Category);
window.location.href = "../Details.html";
}
It doesn't do any thing when i press any items . Any help ?

Pay attention on how you build the string:
href="javascript:ProviderDetails(' + data[i].DoctorName + ',' ......
you need to add the string delimiters:
href="javascript:ProviderDetails(\'' + "data[i].DoctorName" + '\',\'' .....
Your function is declared as:
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category)
{
....
}
Now, because your function expects strings as input you can call your function as:
ProviderDetails('string1', 'string2', .....)
Your javascript loop instead produces:
ProviderDetails(string1, string2, .....)
For javascript now the parameters are considered as variables, i.e., string1 is no more a string but a value contained in the variable string1.
But because you do not have such a variable your function call does not work.
So, the delimiters are important to instruct js to understand the beginning and end of a string.
As a delimiter you can you the symbols: ' or ".
But you need to escape the delimiter itself if you want to use it inside the strings:
var a = 'this isn't a string'; // wrong because the inner delimiter is not escaped.
var a = 'this isn\'t a string'; // OK because the inner delimiter is escaped
Of course if you use inside the string the other delimiter you do not need to escape it.
var a = "this isn't a string"; // this is OK

Related

Regex to replace only some / characters inside strings

How to get regex with replace method? In my case I've got string which uses char / between.
input:
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;
output:
"cn/Nemesis Group/st/2/ic/null/pr/1 - High/es/null/mc/Add/Button/sc/Core/Label/ty/str"
variable mainCategory and subCategory returns string 'Add/Button' and 'Core/Label'
How to replace 'Add/Button' to 'Add%2FButton' and 'Core/Label' to 'Core%2FLabel' without changing any other char?
string.replace("\/", "%2F")
will change all char / to %2F
You can use encodeURIComponent() and decodeURIComponent() to transform this String
Example:
const companyName = "Company",
state = "State",
incCi = "IncCi",
priority = "Priority",
emplSystem = "EmplSystem",
mainCategory = 'Add/Button',
subCategory = 'Core/Label',
type = "Type";
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem +
"/mc/" + encodeURIComponent(mainCategory) +
"/sc/" + encodeURIComponent(subCategory) + "/ty/" + type;
console.log(string)
It sounds to me like you are looking to encode the url. You can use encodeURI in JS to encode a url.
let encodedURL = encodeURI(url);
You can read more about it here.
If you want to encode the string altogether without ignoring any domain related parts, you can us encodeURIComponent()
let encodedURL = encodeURIComponent(url);
You can read more about their differences here.
EDIT:
If you are not encoding a url and you just want to repalce / with %2F only in mainCategory and subCategory then you need to run the regex on the string itself before joining them.
var string = "cn/" + companyName +
"/st/" + state +
"/ic/" + incCi +
"/pr/" + priority +
"/es/" + emplSystem +
"/mc/" + mainCategory.replace("\/", "%2F") +
"/sc/" + subCategory.replace("\/", "%2F") +
"/ty/" + type;

How to keep the next line \n from getting removed inside the email text?

All the \n are removed from the string when the text is put inside mail body .
var valuess = Object.entries(feedBackText);
valuess.forEach(function (key) {
responseText = responseText.concat(' ' + key[0] + ':' + key[1] + '\n');
});
var parsedString = responseText.toString();
window.location = "mailto:myid#gmail.com"+"?subject="+subjectmail+"&body=" +
parsedString;
The following demonstrates how you can solve this using the built-in encodeURIComponent function:
var parsedString = "text on the" + "\n" + "next line";
var link = "mailto:myid#gmail.com" + "?subject=Example&body=" +
encodeURIComponent(parsedString);
console.log(link);

How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}

Get specific part of url

I have a set of urls that i need to get a specific part of . The format of the url is :
http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg
I need to get the 1234567 bit and store that in a var.
Well you can do splits
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".split("/").pop().split("_").shift()
or a regular expression
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".match(/\/(\d+)_\d+\.jpg$/).pop()
You should be able to get it to work with your JSON string by checking the URL with a function. Something like this should work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
$.get("test.php", function (data) {
// now you can work with `data`
var JSON = jQuery.parseJSON(data); // it will be an object
$.each(JSON.deals.items, function (index, value) {
//console.log( value.title + ' ' + value.description );
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
//tr.append("<td>" + value.description + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td class='temperature'>" + value.temperature + "</td>");
tr.append("<td>" + "<a href='" + value.deal_link + "' target='_blank'>" + "View Deal</a>" + "</td>");
myvar = checkForMatches(value.deal_link);
if(myvar == false) {
myvar = value.deal_link; //if no matches, use the full link
}
tr.append("<td>" + "<a href='" + myvar + "' target='_blank'>" + "Go To Argos</a>" + "</td>");
$('table').append(tr);
});
});
Earlier, more basic examples.
You can use a regular expression to find the match.
Something like this would work:
var str = "http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg";
var res = str.match(/.*\/(.*)_1.jpg/);
alert(res[1])
If you wanted to go a little further with it, you could create a function and pass the strings you wanted to test, and it would return the matched value if found, or boolean false if no matches exist.
Something like this would work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
alert(checkForMatches("http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg"))
alert(checkForMatches("this is an invalid string"))
You can see it working here: https://jsfiddle.net/9k5m7cg0/2/
Hope that helps!
var pathArray = window.location.pathname.split( '/' );
to split 1 / 2/ 3/ 4...
So to get path 2 it would be:
var setLocation = pathArray[1];
Well This should do
function getLastFolder(){
var path = window.location.href;
var folders =path.split("/");
return folders[folders.length-1]);
}
Here's the idea: take everything that comes after the final / character, and then take everything within that substring that comes before the first _ character.
var getUrlTerm = function(url) {
var urlPcs = url.split('/');
var lastUrlPc = urlPcs[urlPcs.length - 1];
return lastUrlPc.split('_')[0];
}
You can attribute the url to an 'A' element and use javascript's built in methods to make your life easier:
var parser = document.createElement('a');
parser.href = "YOUR URL HERE";
var fileName = parser.pathname.split('/').pop();
var code = fileName.split('_')[0];
code will have the value you want.
I would use a regular expression and sense it seems you are looking for numbers you can do the regex filter for that.
var path = window.location.pathname,
regFilter = /\d*/g,
filter = regFilter.exec(path);
The regular expression \d narrows your filter search to only look for digits. And the * grabs the group of digits.
Your result is in the filter var. The only thing about this is that the exec returns an array with your original string and the returned result which will be at the 1 index so you'll have to grab it from there like so.
filter[1];

Trouble with regex in javascript; any content within <angular> brackets disappear

I am trying to parse a formula, and display it on screen.
For example I should be able to take <path>T Q, where <path>T cannot change, and Q is a variable. It accepts it,however when printing it on screen again the only thing that will appear is T Q. I want <path>T Q to appear fully.
Other examples of accepted formulae are
(B & A)
~A
~(B&A)
<path>T (B & A)
etc
My code is something like this
var beginPartBUC = '^<path>\\(',
beginPart = '^\(',
unaryPart = '(?:~|<path>T)',
propOrBinaryPart = '(?:\\w+|\\(.*\\))',
subwffPart = unaryPart + '*' + propOrBinaryPart,
endPart = '\\)$';
// binary connective regexes
var conjRegEx = new RegExp(beginPart + '(' + subwffPart + ')&(' + subwffPart + ')' + endPart), // (p&q)
implRegEx = new RegExp(beginPart + '(' + subwffPart + ')->(' + subwffPart + ')' + endPart), // (p->q)
equiRegEx = new RegExp(beginPart + '(' + subwffPart + ')<->(' + subwffPart + ')' + endPart); // (p<->q)
// untilRegEx = new RegExp(beginPartBUC + '(' + subwffPart + ')U(' + subwffPart + ')' + endPart); //<path>(p U q))
As Barmar pointed out, you're writing to html and <path> resembles valid html. You can do this
currentFormula.html('<strong>Current formula:</strong><br>' + wff.ascii.replace(/>/g, ">").replace(/</g, "<"))
As an additional note, backticks are used on StackOverflow like this: `sample code` which produces sample code. This feature is available in comments as well.
Alternatively, in posts (not comments), you can indent each line with a tab or four spaces (easily done by pressing { } in the post editor.

Categories