Javascript: How do fix W3 Validation Error caused by & - javascript

Is there any way to fix the error that a JavaScript & causes in w3 validation? The problem is that i have to use && in a if statement and these two &&'s causes errors in w3 validation.
EDIT:
Same problem with "<" and ">".

There are a few things you can do.
You can enclose it within HTML comments:
<script type="text/javascript">
<!--
if (foo && bar) ...
//-->
</script>
You can enclose it in a CDATA section:
<script type="text/javascript">
// <![CDATA[
if (foo && bar) ...
// ]]>
</script>
You can include in in a file instead:
<script src="foobar.js" type="text/javascript"></script>

The primary answer is: Use JavaScript files for JavaScript, not HTML files, and use the src attribute of script tags. (Combine all your JS into one file, minimize, gzip, etc. for performance.)
But, you can embed JavaScript in HTML if absolutely necessary. Use a valid, modern DOCTYPE and you don't have to resort to comment tags and CDATA sections.
Valid HTML5 example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Example</title>
<script type='text/javascript'>
function foo() {
var a = 1, b = 2;
if (a && b) {
alert("Both");
}
if (a < b) {
alert("a < b");
}
if (a > b) {
alert("a > b");
}
}
</script>
</head>
<body>
<p>Hi there</p>
</body>
</html>
That will also validate as HTML4 strict if you change the doctype to
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
Note that in both cases, you need to be careful about end tags in your script --
This causes the problem:
<script type='text/javascript'>
alert("</td>");
</script>
This solves the problem by prefacing the slash with a backslash (or you can break the end tag up into separate string literals):
<script type='text/javascript'>
alert("<\/td>");
// -or-
alert("<" + "/td>");
</script>
But again, the basic answer is: Don't embed JavaScript within HTML files when you can avoid it, use JavaScript files for that.

Based on your description, I suspect that you're talking about script that's inside an event property in an HTML tag (such as onclick). In that event, the script code needs to be HTML encoded. Elijah hit the nail on the head there.
For example:
<input type="submit" onclick="if(somevar && othervar) callFunc("clicked");">
You do not need to do that inside a <script></script> block.

Escape & with &, < with <, and > with >.

Related

how to isolate js script from the html code?

i'd like to isolate the javascript code from the html code in two diferent files, originally I had this code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
</body>
</html>
<script>
$(document).ready(function () {
$("#body").text("JS Text");
});
</script>
and the output of the <-p-> was the expected "JS Text".
Then I tried to isolate the js script to another file (script.js):
window.onload = function(){
var text = document.getElementById('body');
text.innerHTML ='JS Text';
}
I've also make the reference at the html file:
<script type="text/javascript"src="scripts.js"></script>
but then the output text is no longer the expected (JS Text) but (HTML text)
what else do I need to make the js script work again?
First, it is invalid to place anything after the closing HTML tag, so while your first bit of code worked, it was invalid.
If you remove the JavaScript and place it in its own file, it will continue to work as long as you reference the file properly (use a relative reference and test the file on a web server) and place the script element just prior to the closing body tag so that when the script is processed and attempts to find the right DOM element, the DOM will have been loaded at that time.
FYI:
If you have JQuery in the referenced script file, then your
script that references JQuery will need to occur in the HTML prior
to the script that uses it.
The type attribute in the script tag has not been needed in
several years.
It's not a good idea to name anything body so that you won't cause
confusion with the body element.
Don't use .innerHTML when the string you are working with doesn't
contain any HTML. .innerHTML has security and performance
implications. Use .textContent instead.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
<script src="relativePathToFile.js"></script>
</body>
</html>

How to run a script inside the <title></title> tag of a HTML page?

I have a weird situation where I need to run a script inside of the <title></title> tags. I have no access to any of the others parts of the page, including the <head></head> tags. It has to be within the <title></title> tags (the reason is because we are dealing with an iframe response from a 3rd party server and we don't really have access to the full page.).
What I tried was:
<title>
<script type="javascript">
runMyFunction();
</script>
</title>
The problem is that it interprets the whole thing as a script. Is there anything I could do to tell the browser to run that code as a script and not treat it as a string?
You can't.
Per the HTML5 specification, the only permissible content of the <title> tag is plain text. Other tags, such as <script> tags, cannot be present in the context of a <title>.
<title>[trick</title>
<script type="javascript">
runMyFunction();
</script>
<title>:)]</title>
Everyting between the [] is what you should set as title. Most probably it won't work though, 'cause if I were them I would properly encode whatever string you send, in order not to let you do any tricks...
Can you just rewrite <title> later?
<head>
<title>My Title</title>
<script>
document.title = runMyFunction()
</script>
</head>

Javascript code validates but does not output

I have been working on code to calculate shipping costs. I had the code working in HTML but realized that it needed to be in XHTML 1.0 Strict. Knowing that it worked I started working on the validation errors. I now have it error free but the code stopped outputting the Total Cost. Where am I going wrong here?
updated code
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> "Calculate Shipping" </title>
<script type="text/javascript">
// <![CDATA[
function calculateShipping() }
var price = parseFloat(document.getElementById('price').value);
//This will add $1.50 to any purchases that are less than or equal
to $25.00.
if (price <= 25){
price = (price) + 1.5;
} else {
//return price * 10 / 100
var percentToAdd=(price) * .1;
price=(price)+(percentToAdd);
}
document.getElementById('result').innerHTML='Total Order Cost:
'+price;
// ]]>
</script>
</head>
<body>
<h1>Enter Purchase Price</h1>
<form action="#">
<div id="result">
<input type="text" name="price" id="price" />
<input type="button" value="Submit" onclick=calculateShipping(); return
false;" />
</div>
</form>
</body>
</html>
The browser might be trying to evaluate those CDATA declarations as Javascript (remember that most browsers will parse the XHTML as if it were HTML). Try putting them inside Javascript comments.
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
Another possibility is putting the Javascript in a separate file instead of trying to embed it into the document
<script type="text/javascript" src="shipping.js"></script>
Finally, you might want to check out this similar question: When is a CDATA section necessary within a script tag?
You are missing a final closing }
also use comments on your CDATA statements or remove them (as missingno sez).
Here's what's wrong:
You're missing a closing } on your function;
You're performing a lower-than operation on a string. That's just a really bad habit.
Your CDATA tag may be interpreted as JavaScript.
Instead of using parseFloat in all the wrong places, just put the parseFloat around your variable definition:
var price = parseFloat(document.getElementById('price').value);
Also, make sure you close your brackets. Just put a } on the last line, in this case, and your function will be closed correctly
Finally, you should really put a double slash before each of the CDATA parts. Like missingno said:
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
Comment it out by using single line comments.
PS: try just using HTML5, with this doctype:
<!DOCTYPE html>
Also, you should make sure all your quotes are closed. If you are running this through a debugger and it is giving you no errors, you should really use a better debugger. I've fixed your code and put it in a jsbin, you can see it here. Try putting your code in there next time. I'm sure it'll give you all the errors you're getting.
PS: you might not be getting errors because your "js error debugger" only checks .js files, and you've made your script an inline script. Try putting just the JS code in the debugger next time.

Recognizing mobile numbers from web page

While developing chrome extension for detecting the mobile numbers, I have used javascript included in to the content script. For implementation I used this link for detection but using this javascript are also detecting from html attributes like
file 1
Since, 1234566780 is not a mobile numbers it get detected as a number. How can these html tags can be ignored while performing this replacing task. Is there any javascript function to ignore the HTML tags ?
I think this can be done by implementing the regex of
1. ignoring the characters start with "<" and end with ">"
here is html file,
<html>
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
</script>
<script>
$(document).ready(function () {
$('body').each(function () {
$(this).html($(this).html().replace(/(\d\d\d\d\d\d\d\d\d\d)/g, '$1'));
});
});
</script>
</head>
<body>Vignesh - 9427415949 file 1
</body>
</html>

Why isn't this script working?

I put this into Notepad and saved as an htm. However, when I open it in IE, it just says the text without the <HEAD> and </HEAD>. I have tried encoding it as Unicode, UTF-8, Unicode big Endian, and ANSI.:
<HEAD>
var ifbumper=0
if (ifbumper=0)
{
window.location='/bumper?url=whatever'
}
</HEAD>
You're writing JavaScript code, you need to put it inside of <script> tags. You also need to use == instead of = to compare values, and it's a good idea to put a ; following a line of code.
<HTML>
<HEAD>
<SCRIPT>
var ifbumper=0;
if (ifbumper==0)
{
window.location='/bumper?url=whatever';
}
</SCRIPT>
</HEAD>
You need to wrap JavaScript code inside <script> tags like this:
<head>
<script type="text/javascript">
var ifbumper = 0;
if (ifbumper == 0){
window.location='/bumper?url=whatever';
}
</script>
</head>
The equality operator is ==, not just =. Your if should be aif (ifbumper == 0)

Categories

Resources