Escaping in JavaScript - javascript

How do I make this work?
<a href='javascript:func("Jack'S Birthday")'>Jack's Birthday</a>

Do as follows:
// How about using variables instead?
var emily = "Emily'S Birthday"
var birthdays = {
john: "John'S Birthday"
}
function func(val) {
console.log(val);
}
<!DOCTYPE html>
<html>
<body>
<a href='javascript:func("Jack&apos;S Birthday")'>Jack's Birthday</a>
<br>
Norman's Birthday
<br>
Emily's Birthday
<br>
John's Birthday
</body>
</html>
Explanation:
Keep single quotes within double quotes when you escape using backslash \
Use double quotes within single quotes when you use $apos;
Best of all, use variables, they ease a lot of pain -
a. You don't have to go into html to modify values,
b. these can be declared at one place, or a single file,
c. They can be fetched from back-end
d. Best yet, no need to deal with quotes!

Apparently you can't escape characters within HTML attributes. The proper way to go would be to use HTML entities like &apos; :
<a href='javascript:console.log("&apos;")'>click me</a>
See How to properly escape quotes inside html attributes?.

If possible, do it this way
<html>
<header>
<script>
function func(x) {
alert(x);
}</script>
</header>
<body>
Birthday
</body>
</html>

Convert to NCR. This should work.
<html>
<a href='javascript:func("Norman'S Birthday")'>Birthday</a>
</html>
Or.
<html>
<a href='javascript:func("Norman'S Birthday")'>Birthday</a>
</html>

Related

Get a part of string from a page source code (information is present in HTML)

How can I look for a keyword in a HTML source code and get a value from the code using Pure JS. There are multiple code tags and I am looking to extract the value 12345 and it can be in any <code> block which doesn't have a unique ID or class. The keyword (word to find in any code tag) to find would be "THIS_IS_WHAT_IAM_LOOKING_FOR".
Example:
HTML source code:
<html>
<body>
(some HTML goes here)
<code style="display: none">
wlkdw,dmnewf4oi4j4f4knkf4kjfkfjk;fefiekf;flegelgjelkghjreg;THIS_IS_WHAT_IAM_LOOKING_FOR12345,95849;fefjefefmdl;fljegflegc;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
</code>
<code style="display: none">
fffffffffffekjfekfjekfjrgkrgkjkthjtkhjtkhjtkhjkthp;gkrg2;4l3lgfrgrgkrg9;fefjefefmdl;fljegfleg w;c;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
</code>
</body>
</html>
You can use split() to get the part of the string you are interested in, for instance, in your case, i assume you have the mentioned text before the value and a comma after:
const d0 = htmlCode.split('THIS_IS_WHAT_IAM_LOOKING_FOR')[1] // After this text
.split(',')[0]; // Before this
console.log(d0);
Example working in stackBlitz
https://stackblitz.com/edit/js-hqqvrl?file=index.js
There are probably more elegant ways to do this, but this one should work.

Pig Latin translator using a While Loop in Javascipt

My son is teaching himself JavaScript. (He’s too young to have an account here.) He’s trying to write a Pig Latin translator using a “while loop.” The basic question he right now is how to sequence the code - so the user types in the word, then the program translates it, then the result appears in the alert box. He’s brand new to this, so if anyone has any friendly feedback it would be much appreciated.
Here’s what he’s got:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="Javascript">
<!-- Beginning of JavaScript -
</SCRIPT>
</HEAD>
<BODY bgcolor="Blue">
<h3> Type some text then click TRANSLATE. </h3>
<FORM>
<INPUT NAME="wordToTranslate" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="TRANSLATE" onClick="alert(form.wordToTranslate.value)" style="font-size:1em;background:lime">
</FORM>
<script>
while (wordToTranslate.substring(0, 1) = bcdfghjklmnpqrstvwxyz) {
console.log(var wordWithoutFirstLetter = wordToTranslate.slice(0, 1);
var wordWithoutLastLetters = wordToTranslate.slice(1) var wordToTranslate = wordWithoutFirstLetter + wordWithoutLastLetters;
++
wordToTranslate + ay
</script>
Oh my, there are a lot of errors in this code. I would really recommend trying some easier examples first. But to save you some time in the future, here are (some) of the issues I see in your JavaScript. Every one of these will cause an error and stop the code from running.
The primitive strings are not inside quotation marks or apostrophes (for instance, bcdfghjklmnpqrstvwxyz should be "bcdfghjklmnpqrstvwxyz")
Attempting to log syntax rather than a string (or object that can be converted to a string): console.log(var ...) will cause an error
Using an increment (++) operator on a string variable...
some parentheses are missing closing parentheses, and the curly bracket has not closing curly bracket
you never actually get the string to use from the HTML element (i.e., the "value" of the <INPUT>).
After working with some easier examples first and building up to this, I would suggest googling a JavaScript pig latin example and using it as a reference to learn the more complicated concepts (like matching the first letter to a consonant). Good luck!
Since you're looking for general help, I would gently suggest that if he's learning JavaScript and HTML that he learn the newer versions, namely HTML5 , ES6+, and CSS3.
Below is essentially what he has so far--Pig Latin translation code not included--but moved to the newer standards.
'use strict';
const btnTrans = document.getElementById('btnTrans');
const txtWord = document.getElementById('txtWord');
btnTrans.addEventListener('click', translate);
function translate() {
console.log(txtWord.value);
}
body {
background-color: blue;
}
button {
font-size: 1em;
background:lime
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<input name="wordToTranslate" id="txtWord" type="text">
<button type="button" id="btnTrans">Translate</button>
</form>
</body>
<script src="script.js"></script>
</html>
Note the DOCTYPE on the html. Also, all of the HTML elements are lowercase and the attribute values are quoted. JavaScript side, the event listener for the button click event is wired up in the JavaScript code, not in the HTML. The variables are set using const, which is scoped differently than var. I've also moved the inline styles to a CSS file and gotten rid of the old, deprecated ones like bgcolor.
Separating the code into separate files like this creates a clear responsibility for each part of the overall app: the HTML is the view; the CSS styles that view and can be overridden or changed in the future; the JavaScript acts as the controller.
I don't really expect this to be selected as the answer to this question; rather, it's general advice for a general question and new-to-the-web-world programmer. Welcome aboard! =)

HTML input into Javascript

I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button
Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.
I think you mean:
var r = document.getElementById("radius").value;
getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);
Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;
You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.
Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.

JQuery .html can not adding variable value into a href

I want to create a list of news on my webpage. When mouse click on the content, there will be a url available. For example apple news
Here are my sample codes, my problem is: when I try to add a variable's value into the href, like href="www.search.com?keyword="+var.keyword, it will display apple news
Actually there are a 50 objects in the variable model, so it will having 50 model.link and model.keywords, please help me to change the sample code which works on w3cshools.com "try it youself". I tried 10 times by really don't know the how to fix it, thanks!
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<!-- should end this tag-->
var model=[{"link":"http://www.google.com?keyword=","keyword":"apple" "content":"This is a news"}]
<!-- miss a ";" at the end of line -->
</script>
<script>
$(document).ready(function(){
$("p").html("Click <a href=model.link+model.keyword>this link</a>");
<!--Finally this works: $("p").html("Click <a href='"+model[0].link+model[0].keyword+"'>this link</a>");-->
});
</script>
</head>
<body>
<p>A content</p>
</body>
</html>
Quote properly:
$("p").html("Click this link");
you missed comma in your model variable::
var model=[
{
"link":"http://www.google.com?keyword=",
"keyword":"apple",
"content":"This is a news"
}
];
And since its array of object , you need to access it like model[0].link to get first object from model array, like:
$(document).ready(function(){
$("p").html("Click <a href='"+model[0].link+model[0].keyword+"'>this link</a>");
});
Put the link correctly
$("p").html("Click <a href='"+model.link+model.keyword+"'>this link</a>");
This is what you need:
var model=[ { link:'http://www.google.com?keyword=', keyword: 'apple', content: 'This is a news'} ];
$.each( model, function( key, value ) {
$('p').append('Click this link');
});
You need to loop through the array of objects and get values. You can use $.each to make this easy since you are using jQuery though you can just as easily do this with vanilla Javascript, I would also get in to the practice of wrapping strings in single quotes in Javascript, that way you can add double quotes in a nice readable syntax to HTML strings you will be adding to the DOM.
Note that I did not use quotes for object keywords too.
See fiddle:
http://jsfiddle.net/r8MQ9/1/

Java Script works with a single value but not with two

I have a Java Script that stops working when I try to input two values. This is the script that works:
<HEAD> <script type="text/javascript">
function addsuggest(name)
{
document.getElementById("recipients").innerHTML=document.getElementById("recipients").innerHTML+name+".L ";
}
</script> </HEAD>
<a href=javascript:onClick=addsuggest('3') >click here<a/><br>
<span id=recipients style="color:blue;"> </span>
Nothing fancy. It just adds 3.L in blue color to the end of a line.
I want this function to do some other things so I change function addsuggest(name) to function addsuggest(name, id) and onClick=addsuggest('3') toonClick=addsuggest('3', 'John')
These are the symptoms I have:
It won't work. I tried making it a button. Again it won't work.
When I hover over the link it shows javascript:onClick=addsuggest('3' and not the rest. So it's stopped reading it at the comma.
Rest of the page content goes blue as if it's link but not clickable.
This is the simplest thing I've done with Java Script. It's just inputting values and then printing it. So, what's the matter?
You need quotes surrounding the href attribute (and should place them around all other attributes), otherwise the single quotes around the function parameters will break the link:
<HEAD> <script type="text/javascript">
function addsuggest(name, id)
{
document.getElementById("recipients").innerHTML=document.getElementById("recipients").innerHTML+name+id+".L ";
}
</script> </HEAD>
<a href="javascript:onClick=addsuggest('3', 'John');" >click here<a/><br>
<span id="recipients" style="color:blue;"> </span>
...
and for readability:
function addsuggest(name)
{
document.getElementById("recipients").innerHTML += name + ".L";
}

Categories