-7

I have the following Javascript code, however it is not working. Can anyone help me out with this?

These are the things that I want to achieve:

  1. increase the number of games to those requested by the user p1
  2. check if only valid numbers have been entered p2
  3. line break between the first 10 and the second 10 p3

Any assistance?

<html>
    <head>
        <title>processing</title>
    </head>

    <body>
        <form name="processing" action="processing.php" method="POST">
            <input type="hidden" name="check_submit" value="1" />
            <p>Please select the numbers of players:</p>
            <select>
                <SCRIPT Language="JavaScript">
                    for (i = 1; i <= 8; i++) {
                        document.write('<option value="' + i + '">' + i + '</option>');
                    }
                </script>
            </select>
            <input type="submit" />Scores From Game 1:
            <SCRIPT Language="JavaScript">
                for (i = 0; i < 20; i++) {

                    document.write('<input type="number" name="scores[]" min="0" max="10" value="0"/>')

                }
            </script>
            <input type="submit" />
        </form>
    </body>

</html>
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
  • 3
    what do you mean by not working. what do you expect? what is happening? – Ben McCormick Apr 23 '13 at 17:09
  • 1
    Although you wrote some code, it smells like a "do my homework for me SO!" question... – akluth Apr 23 '13 at 17:09
  • You should go read a javascript tutorial: http://www.w3schools.com/js/ – doliver Apr 23 '13 at 17:11
  • 1
    @doliver http://w3fools.com/... – Niet the Dark Absol Apr 23 '13 at 17:11
  • I can get it to work however, I have been advised not to use document.write? Is this correct? – user2312345 Apr 23 '13 at 17:11
  • A w3schools.com tutorial? Then you will have 2 problems. – UpTheCreek Apr 23 '13 at 17:12
  • If anyone can suggest a better tut then by all means. The point is that giving a solution to this very specific problem I don't feel is the correct solution in this situation. – doliver Apr 23 '13 at 17:14
  • This is what my tutor advised me: do an id on the select and document.getElementById('selectid').innerHTML += " – user2312345 Apr 23 '13 at 17:14
  • innerHTML is also frowned upon, my answer explains why – Rick Viscomi Apr 23 '13 at 17:17
  • You need to read about DOM honestly. Basically, you're fetching the element on the page with id 'selectid' and setting it's inner html(html inside that tag) to 'something or other'. This is one way of resetting the contents inside the select tag – doliver Apr 23 '13 at 17:19
  • 1
    People say to not use `document.write` because it can be misused. Your use of it is correct. There will always be people who say *"never use this or that"* because there can be misuses of the tool. I disagree with this sort of paranoid approach to development. What you should do is come to understand the tools you use, and use them correctly. – silly little me Apr 23 '13 at 17:20
  • Here's another reference: http://reference.sitepoint.com/javascript/Document – doliver Apr 23 '13 at 17:21
  • 1
    Brace yourselves for an overwhelmingly informative answer that ironically might make it worse for user2312345, and a thread of tut site links. `document.write` is a gun that you can use it wisely or to shoot yourself in the foot. If it ain't broke, don't fix it. But if you're set to learn new techniques, surely there are tons of sites for these. – Terry Young Apr 23 '13 at 17:22
  • @sillylittleme `document.write` is never used in a way that is more efficient than alternate methods. – Rick Viscomi Apr 23 '13 at 17:22
  • @RickViscomi: Do you mean processing efficiency? That's one consideration, but not the only one, and I've not measured it. The use of `document.write` in the question is very short and clear. There's no real issue with it that I can see. – silly little me Apr 23 '13 at 17:24
  • @sillylittleme Writing code for its simplicity is a pitfall of web development. We, the developers, are not the consumers of the code. The end users are. The end users care about load time and such. It's our responsibility to write code to the established best practices of web development to ensure that our pages load as quickly as possible. – Rick Viscomi Apr 23 '13 at 17:29
  • 1
    @RickViscomi: Tell that to all the developers who load jQuery in the head of the document just to implement a few lines of simple JavaScript. Happens a lot. I'm not convinced that something like this will make any noticeable difference compared to using `document.createElement` or sending the full HTML over the network. – silly little me Apr 23 '13 at 17:33
  • @user2312345 Or you can tell your advisor that the advice does not apply to this case. If it ain't broken, don't fix it. **Use** `document.write`, **then** eventually something will screw up, and **only then** you will learn what the advice really meant, **then** move on to chapter two: *innerHTML*... **then** the other stuff. If you think there's a shortcut in this field, think again. – Terry Young Apr 23 '13 at 17:41
  • @sillylittleme no matter how many people do it the wrong way, it's still wrong – Rick Viscomi Apr 23 '13 at 17:42
  • @RickViscomi: You seem to be stuck in a mindset of right and wrong. That's far too simplistic for software development. A good developer understands the pros and cons of every approach, balances them, and makes intelligent decisions. A good developer doesn't need to substitute simplistic rules for intelligent decisions. – silly little me Apr 23 '13 at 17:48
  • Reminds me of the good ol' days when people argue about outerHTML – Terry Young Apr 23 '13 at 17:51
  • Let me rephrase: there are well established best practices. Deviating from the best practices is bad. Sometimes there are good reasons to do so. – Rick Viscomi Apr 23 '13 at 17:54
  • @RickViscomi: define "wrong". Six years ago, "right" was using innerHTML and outerHTML. What was right one day could be wrong the next, *and vice versa*. Furthermore, I can name you one use case where document.write is necessary, and one use case where innerHTML significantly outperforms `removeChild`. I can also name you one case where putting a light script in the HEAD of your document actually improves your page. Please stop thinking of "right" and "wrong" and start thinking of 'advantages' and 'drawbacks'. – Sébastien Renauld Apr 23 '13 at 18:01
  • Today's best practices are tomorrows anti-pattens. Trends come and go. Be skeptical of trends. – silly little me Apr 23 '13 at 18:05

3 Answers3

2

Rather than using JavaScript, why not just use the raw HTML?

...
<select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
  <option>8</option>
</select>
...
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
<input type="number" name="scores[]" min="0" max="10" value="0"/>
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • (Standing in enlightenment, epiphany and awe) I can't tell how much I am so tempted to vote this up, you just made my day :) – Terry Young Apr 23 '13 at 17:14
  • Probably because of extra download and higher maintenance when making changes. That's part of the point of being able to generate markup using `document.write`. – silly little me Apr 23 '13 at 17:28
  • This is the real solution. As for @sillylittleme, the trade-off is search engines actually seeing the fields along with browsers with JS disabled. – Sébastien Renauld Apr 23 '13 at 17:29
  • @SébastienRenauld: Something tells me that's not a real consideration here. It's certainly something that needs to be taken into account when making a decision though. – silly little me Apr 23 '13 at 17:30
  • The OP seems to be asking for a solution that enables dynamic generation of HTML. This is a cute answer but doesn't address the OP's needs. – Rick Viscomi Apr 23 '13 at 17:31
  • @RickViscomi ...which is why I said 'tempted' :) – Terry Young Apr 23 '13 at 17:33
  • 1
    Hi Rick, That is exactly what I am looking for. This is because the number of players can change in each game. I do not want the extra cells taking up space or it to be fixed for a certain number of players. This is why I want the dynamic generation of html. – user2312345 Apr 23 '13 at 17:35
  • 1
    Yeah, this should a comment. It's not like OP needs to actually *see* all the HTML written out to understand it. – silly little me Apr 23 '13 at 17:36
  • At the same time, why isn't the HTML generated by the server? Why is Javascript handling the dynamics like this? The PHP should take care of something like this...producing this answer. – Ian Apr 23 '13 at 17:37
  • @Ian: The more you can offload to the client, the better. Less work for the server, and less to transfer over the network. It presumes of course that JavaScript is a requirement to use the page *(or at least some features)*. – silly little me Apr 23 '13 at 17:40
  • @sillylittleme: accessibility standards say hi. You are partly right - however, JS should be used to provide *enhancements*, unless you are certain that your use case *requires* JS (and not the other order of priorities). Ian is right, though - this would have costed PHP under 600 bytes of RAM to generate and very few CPU cycles, possibly less than JS on the client. If the loop was heavier, there might be a use case. – Sébastien Renauld Apr 23 '13 at 17:53
  • @SébastienRenauld: Yeah, I should have prefixed my last comment with the word "conceptually". I'd imagine this site won't get 10,000 requests/second. – silly little me Apr 23 '13 at 17:55
  • @sillylittleme: ultimately, there's no white and no black, just shades of grey. One approach saves server clock cycles, bandwidth and RAM by offloading at the cost of usability, the other does the opposite. :-) – Sébastien Renauld Apr 23 '13 at 17:57
  • @SébastienRenauld: Exactly! :) There's far too much religion in development. I believe in the separation of church and software. – silly little me Apr 23 '13 at 18:04
1

Whoever suggested it is correct - avoid document.write in favour of document.creatElement due to document.write's ability to break DOM usage. Not just this, but you're breaking semantics by putting a script in a select element - bad.

Let's re-write your code. Suppose you have this:

<select id="NumPlayers">
</select>

And your current code:

 for (i = 1; i <= 8; i++) {
               document.write('<option value="' + i + '">' + i + '</option>');
 }

To stop all hell breaking lose, you can re-work it into something like this:

window.onload = function() {
   var selectTag = document.getElementById("NumPlayers");
   for (var i = 0; i <= 8; i++) {
       var c = new Option(i,i);
       selectTag.add(c);
   }
};

This will do three valuable things:

  1. It will prevent you from breaking your DOM
  2. It will be semantically correct at the end (no script->select child behaviour)
  3. It will wait until the page is loaded to modify the DOM.
Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66
  • 1
    How could the use of document.write as shown by the OP break the DOM?! – bfavaretto Apr 23 '13 at 17:26
  • @bfavaretto: I said document.write *can* break DOM structure, not that it will. However, I know at least one browser that barfs up if you give it a select -> script -> option sequence. – Sébastien Renauld Apr 23 '13 at 17:28
  • Instead of `document.createElement("option")`, you could use `var c = new Option(i, i);` and instead of `selectTag.appendChild(c);`, could use `selectTag.add(c);`. Just alternatives, not important – Ian Apr 23 '13 at 17:30
  • 1
    Okay, that makes sense; select > script is indeed invalid html, but could be avoided by document.writing the select too. – bfavaretto Apr 23 '13 at 17:31
  • @Ian: thank you for the modifications. Putting them in. – Sébastien Renauld Apr 23 '13 at 17:31
0

Instead of using document.write to dynamically insert HTML content, use the DOM APIs:

o = document.createElement('option');
o.value = i;
o.appendChild(document.createTextElement(i));
select.appendChild(o);

document.write is frowned upon because browser pre-parsers are unable to optimize the HTML content inserted using this method. If you tried to do something like document.write('<img src="pic.jpg"/>');, the browser will have to wait until the JavaScript is parsed and executed before it can load the image. When inserted normally, the pre-parser is able to spot the image and preload pic.jpg.

Another reason why it's frowned upon is because the JavaScript must be in the exact location in which you want to insert the HTML. This causes fragmented code scattered throughout the HTML document, which is hard to maintain and blocks the rendering of HTML later in the page.

Rick Viscomi
  • 8,180
  • 4
  • 35
  • 50
  • "because the JavaScript must be in the exact location in which you want to insert the HTML" - well, the **execution** of the statements must be where you want the HTML to end up. You could easily put this code in a function, in the `` and then only call the function where you want the `document.write` to happen – Ian Apr 23 '13 at 17:20
  • JS in the head is even worse! ;) But you're right, the function definition could be anywhere. You're still left with the problem described, only with a smaller line of code. – Rick Viscomi Apr 23 '13 at 17:21
  • How is JS in the head worse? – Ian Apr 23 '13 at 17:22
  • http://stackoverflow.com/questions/8249013/why-put-javascript-in-head http://www.stevesouders.com/blog/2010/12/06/evolution-of-script-loading/ http://developer.yahoo.com/performance/rules.html#js_bottom – Rick Viscomi Apr 23 '13 at 17:23
  • Those are opinions. There's nothing wrong with it. It's perfectly fine to put stuff in the ``. It's far from "worse". You can use `defer` or `async` attributes if it's that important – Ian Apr 23 '13 at 17:32
  • 2
    My god, the amount of "omg this is bad! I don't know why but it's bad". Why people say that it is bad form to put JS in the head is because most browsers can only load two concurrent scripts at once, and will freeze rendering at this point until they're done. If you have less than two script tags, the head argument is irrelevant. The reason to put script tags all the way at the bottom of the page is so that if the browser freezes rendering, the page is already fully rendered, that's all. – Sébastien Renauld Apr 23 '13 at 17:33
  • I was in the middle of writing up a nice, logical reply but the latest comments make it obvious that there is no hope in changing these minds. I'll let Steve Souders and the Yahoo Exceptional Performance team speak for themselves. – Rick Viscomi Apr 23 '13 at 17:38
  • @RickViscomi: Everything has been said: browsers can only do two parallel downloads on the same hostname at any given time, and browsers will freeze the rendering process during a script render unless defer is up. That doesn't mean that every script always has to be at the bottom. AMD says hi and casually reminds you that a small signature and little to no immediate processing is perfectly fine in the head of a document. – Sébastien Renauld Apr 23 '13 at 17:43
  • 1
    (And just to add fuel to the fire - the last page you linked, from yahoo based on performance and saying that JS in the head is a bad thing... Loads YUI on the head of the document. Why do they do that? Because YUI contains an async module loader) – Sébastien Renauld Apr 23 '13 at 17:45