views:

183

answers:

3

Hello everybody. I am trying to use JavaScript to start a marquee when a user puts their name into a textbox and then clicks a button. I've got an idea as to how to do it, but my script never fully works. Any help is appreciated!

Here's what I have so far:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<title></title>
<script type="text/javascript">
    function StartMarquee() {
        var text = document.getElementById(namebox);
        if (text != null) {
            document.write("<marquee behavior='scroll' direction='right'>Hello " + text + "!</marquee>");
        }
        else {
            alert("Enter your name first!!!");
        }
    } 
</script>
</head>
<body>
<table style="margin:0px auto 0px auto;">
<tr><td>Enter your name!</td>
<td><input type="text" id="namebox"/></td>
<td><input type="button" value="Enter" onclick="StartMarquee()"/></td></tr>
</table>
</body>
</html>
+1  A: 
var text = document.getElementById(namebox).value;
N 1.1
P.s. do read about unobtrusive javascript.
N 1.1
+1  A: 

You probably don't want to use document.write for this-- use document.createElement('marquee') to create the element, and then add it to the body of the page. You can set attributes like direction on the element you get back, and set its innerHTML to the text you want in the marquee.

(P.S. Marquee? Really?)

quixoto
ya seriously! marquee?
N 1.1
Yep really. Marquees aren't my favorite either, but I'm doing this for a competition with one of my friends.
APShredder
@APShredder: competition. Good.
N 1.1
+3  A: 

Your JavaScript has a few problems.

  1. You are passing an undefined variable namebox to getElementById. You need to put this in quotes ('namebox').
  2. You need to check the value of text against the empty string, not null.
  3. You need to use the value of the input (text.value as opposed to just text) in the element you're creating.

Here is what your code would look like with these fixes:

function StartMarquee() {
  var text = document.getElementById('namebox');
  if (text.value !== '') {
    document.write("<marquee behavior='scroll' direction='right'>Hello " + text.value + "!</marquee>");
  }
  else {
    alert("Enter your name first!!!");
  }
} 

Some other general suggestions:

  1. Don't use document.write. Instead, use DOM methods to create a new element and insert it into the DOM.
  2. Use unobtrusive JavaScript. Attach your behavior after the document loads instead of using inline event handlers.
  3. Use === and !== for conditions to avoid type coercion and to ensure you're getting the result you think you are.
  4. Never, ever use marquee.
Jimmy Cuadra
+1 for Never, ever use marquee.
TiansHUo