Petrie
Petrie

Reputation: 13

Javascript Validation w3c

I'm trying to show/hide content in the following doctype: !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"

Here's my javascript:

<script type="text/javascript"> function question(clicked) {
      var q = document.getElementsByTagName("div");
      for(var x=0; x<q.length; x++) {
            title = q[x].getAttribute("title");
            if (title == 'q') {
                  if (q[x].id == clicked) {
                        if (q[x].style.display == 'block') {
                              q[x].style.display = 'none';
                        }
                        else {
                              q[x].style.display = 'block';
                        }
                  }else {
                        q[x].style.display = 'none';
                  }

           }
      } } </script>

On Validation, it returns these errors: 1. Error Line 9, Column 30: character ";" not allowed in attribute specification list

        for(var x=0; x<q.length; x++) {
  1. Error Line 9, Column 30: element "q.length" undefined

        for(var x=0; x<q.length; x++) {
    
  2. Error Line 25, Column 9: end tag for "q.length" omitted, but OMITTAG NO was specified

  3. Info Line 9, Column 21: start tag was here

        for(var x=0; x<q.length; x++) {
    

I'm learning Javascript now, and have tried to Google & fix this about 3 dozen ways by now. Can anyone help me? If I need to try a different script to show/hide, at this point, I'd scrap what I have and do it.

Thanks in advance!

Upvotes: 1

Views: 2593

Answers (2)

Kris C
Kris C

Reputation: 2848

If you move your javascript functions into an external file, and then link to that file from your page head section, then the validator doesn't have to worry about them.

e.g.

<script src="functions.js" type="text/javascript"></script>

This also allows you to reuse functions across multiple pages without repeating the code.

A further benefit is that the user's browser will cache the js file the first time it encounters it, so on subsequent pages the javascript functions file will be retrieved from cache, rather than being downloaded with the page.

Upvotes: 1

Rob W
Rob W

Reputation: 349262

Use CDATA sections. The < has a special meaning for the parser.

<script>
//<![CDATA[
 ...JavaScript code..
//]]></script>

The validator has detected a <, and attempts to parse a new tag <q.length. When the semicolon is spotted, the parser don't know how to handle it, and throws an error. By using CDATA, you effectively say "Anything inside this section should be interpreted as plain-text, and not be parsed.

Paste your code at http://validator.w3.org/check (validate by direct input), using the following settings: "Validate Document fragment, XHTML 1.0".

Upvotes: 6

Related Questions