I'm working in a proprietary system that has the ability to add HTML and Javascript to create custom pages. The system has the ability to insert user profile fields into the HTML/Javascript a mail merge like tag. In a project I'm working on I'm using a value from one of the users fields (User_Region) to append to a URL and create a personalized link to another system for each user.
I have been able to append the URL successfully when the value is numeric (12345) but not when it is text or alphanumeric. For example neither "Florida" nor "123456a" work.
Here's the code that I am using:
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = {User_Region};
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
In the code {User_Region} is the mail merge tag that I use to insert the variable from the user profile field. If the region variable is numeric like 123456 it works perfectly and it will output a URl like this:
https://www.mywebsite.com/index.php?id=123456
However if the region variable is text or alphanumeric like Florida or 123456a then the script does not work. Document.write does not output anything. It seems like the function either stops or breaks. I'm guessing this has to do with a data type issue, but I can't seem to figure it out.
If I hard code the variable as a string like this the function works perfectly.
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = 'Florida';
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
The above code will output a correct URL like this:
https://www.mywebsite.com/index.php?id=Florida
I have tried numerous ways to add the single-quote marks to the {User_Region} variable without success.
Does anyone have a suggestion for how I can make this work?
Thanks in advance for your assistance!
Have you tried encapsulating it in quotes as such:
var userRegion = '{User_Region}';
Because I guess your framework just replaces the {User_Region} with something else, please inform me if I got it wrong. I didn't quite get what this tag is. You see, in JS, curly braces are used to define Objects.
Related
I'm working on a drive thru app project that uses firebase and JavaScript to display the menu information. I planned to use a template text for displaying everything and it all worked fine. I was even able to make a variable = the value of a field in firebase, but I'm unable to alter that new value. I wanted to replace all spaces with underscores since that is how I named the pictures in my project but it seems to just ignore this command. Here is the code:
let itemName = menuItem.name;
itemName.replace(" ", "_");
console.log(itemName);
Does anyone know of a solution to this?
Javascript's String.prototype.replace function doesn't edit strings in-place, it creates a new one. As well, when doing simple string replacement, it only replaces the first instance - you want replaceAll. This code will do what you want:
let itemName = menuItem.name;
let newName = itemName.replaceAll(" ", "_");
console.log(newName);
I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')
Javascript newb here. Creating a bookmarklet to automate a simple task at work. Mostly a learning exercise. It will scan a transcript on CNN.com, for instance: (http://transcripts.cnn.com/TRANSCRIPTS/1302/28/acd.01.html). It will grab the lead stories at the top of the page, the name and title of the guests on the show, and format them so that they can be copy pasted into another document.
I've come up with a simple version that includes some jQuery that grabs the subheading and then uses a regular expression to find the names of the guests (it will also exclude everything between (begin videoclip) and (end videoclip), but I haven't gotten that far yet. It then alerts them (will eventually print them in a pop-up window, alert is just for troubleshooting purposes).
I'm using http://benalman.com/code/test/jquery-run-code-bookmarklet/ to create the bookmarklet. My problem is that once the bookmarklet is created it is completely unresponsive. Click on it and nothing happens. I've tried minimizing the code first with no result. My guess is that cnn.com's javascript is conflicting with mine but I'm not sure how to get around that. Or do I need to include some code to load and store the text on the current page? Here's the code (I've included comments, but I took these out when I used the bookmarklet generator.) Thanks for any help!
//Grabs the subheading
var leadStories=$(".cnnTransSubHead").text();
//Scans the webpage for guest name and title. Includes a regular expression to find any
//string that starts with a capital letter, includes a comma, and ends in a colon.
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
//Joins the array created by scanForGuests with a semicolon instead of a comma
var guests=scanForGuests.join(‘; ‘);
//Creates an alert in the proper format including stories and guests.
alert(“Lead Stories: “ + leadStories + “. ” + guests + “. SEE TRANSCRIPT FIELD FOR FULL TRANSCRIPT.“)
Go to the page. Open up developer tools (ctrl+shift+j in chrome) and paste your code in the console to see what's wrong.
The $ in var leadStories = $(".cnnTransSubHead").text(); is from jQuery and the link provided does not have jQuery loaded into the page.
On any modern browser you should be able to achieve the same results without jQuery:
var leadStories = document.getElementsByClassName('cnnTransSubHead')
.map(function(el) { return el.innerText } );
next we have:
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
var guests=scanForGuests.join('; ');
scanForGuests IS a regular expression, you never actually matched it to anything - so .join() is going to throw an error. I'm not exactly sure what you're trying to do. Are you trying to scan the full text of the page for that regex? In that case something like this would be your best bet
document.body.innerText.match(scanForGuests);
keep in mind that while innerText removes html markup, it's far from perfect and what pops up in it is very much at the mercy of how the page's html is structured. That said, on my quick test it seems to work.
Finally, for something like this you should use an immediately invoked function or you're sticking all your variables into the global context.
So putting it all together you get something like this:
(function() {
var leadStories = document.getElementsByClassName('cnnTransSubHead')
.map(function(el) { return el.innerText } );
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
var guests = document.body.innerText.match(scanForGuests).join("; ");
alert("Leads: " + leadStories + " Guests: " + guests);
})();
So the basic rundown is that I'm trying to create a rudimentary means of flagging inappropriate content on our web mapping application.
Within a function that dynamically creates content for the sidebar of the webmap when the user clicks on a point I have this piece of code that should generate an image of a flag.
When the user clicks the flag, I want to run the function flagContent which should pass a url string into the function. From within this function I would then be able to
write it to a database later on (though I haven't made it this far yet).
Here are some code snippets I have been working with.:
1.This is where the flag image is generated
content += "<p class='info'><img id='flag' onclick='flagContent(" + attachmentInfo.url + ")
'src='assets/flag.png' style='height:15px'>Flag as inappropriate...</p>";
This is the connected function
function flagContent(imageUrl){ console.log(imageUrl)}
So basically the url is a string and I'd like to be able to manipulate it within the flagContent function. Unfortunately I can't get it to work. When I pass a numerical parameter such as attachmentInfo.objectID I do not run into the same problem.
For what it's worth I also get this error:
Uncaught SyntaxError: Unexpected token :
Any help would be greatly appreciated. Let me know if there is additional information that could help to solve this. Thanks!
I'm assuming that attachmentInfo.url would return a URL, which should be a string and it just needs to be surrounded by quotes. Since you've already used both types of quotes, you will have to escape some quotes.
content += "<p class='info'>";
content += "<img id='flag' onclick=\"flagContent('" + attachmentInfo.url + "')\" src='file.png'/>";
content += "Flag as inappropriate...";
content += "</p>";
Doing this makes the final out put look like this:
<p class='info'>
<img id="flag" onclick="flagContent('http://example.com')" src='file.png'/>
Flag as inappropriate...
</p>
The problem you had was that the URL was not surrounded by quotes, and it saw flagContent(http://example.com) and didn't know what to do with those bare words not in a string.
I want to call a javascript function from my ASP.NET (C#) code, I want to pass a variable (string) with another string like below:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text'+'"+myString+"'<br/>'another text);");
how should I pass these values? also I want to have new line in my tooltip (<br/>), what should I do? I've tried several ways (using ', + and other methods) to send all these values but I get javascript error, is there any sample? please help me
thanks
In that function, you could use the server side code tag.
var string = "<% = myString%>"
You are very close, keep in mind that when controls are generated on the server they are 'unrolled' into HTML on the client -- in other words the '+' sign is unnecessary as the client will only ever see the string (it has no notion of which part of the attribute value was generated in code vs. which part is hard coded on the server).
var toolTip = string.Format("This is text was added on {0}:{1}<br />this text is hard-coded", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()
var attributeValue = string.Format("tooltip.show('{0}')");
tag.Attributes.Add("onmouseover", attributeValue);
Try this:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text','"+myString+"<br/>another text');");
Two ways:
Method 1 (Jon Martin's way): Have a javascript variable populated by server information
Create a javascript variable on the aspx page: var myString = '<%= _mytring %>';
Populate _mystring on the code behind: public String _mystring = "your value";
Method 2: Just dump the variable out from the server side
Page.ClientScript.RegisterStartupScript(getType(Page), "var myString = '" + "your value" + "';", true);