Getting data from the user

Where are we?

You know how to show and hide elements, change their text, and add and remove classes. You know how to tie these things to click events.

Now lets ask users questions, and do things with their answers. Even more w00f!

Let’s do it!

There are lots of ways to get data from users. The most familiar way is to use Web forms, so let’s start there.

Form processing is quite complicated, so we’re not going to look at it all here. In fact, we’re going to take just a couple of pieces, and use them in ways that some Webers will object to.

Calm down, Webers! We’ll get to correct form processing later. But for now, let’s keep it simple, so we can start exploring.

Forms are created with HTML tags. We’ll use two of them here: the <input> tag and the <button> tag.

Getting text data

The <input> tag is used for a lot of different things in HTML. We’ll just use one version of it, the one that creates text input fields.

Here’s an example:

<input type="text" id="my_field">

Here’s what this looks like in your browser:

The type attribute tells the browser what type of field you want. There are check boxes, radio buttons, and others. Let’s stick to text for now.

Buttons

The other tag is <button>. Here’s an example:

<button type="button" id="go">Click me!</button>

Here’s what it looks like in your browser:

Buttons looks different on other sites. I’ve used CSS to make CoreDog’s buttons match the rest of the CoreDogs look. Part of the branding of this site.

There are two types of buttons, regular buttons and submit buttons. We’re using the regular buttons here. That’s what type="button" tells the browser.

The text inside the tag – Click me! or whatever – supplies the button’s caption, that is, the text on the button.

Hello world!

Time for the obligatory “hello world” example. We’ll do it in stages.

Let’s do the first step, just make the HTML and a button that does something. Please have a look at this page.

Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title>Hello world!</title>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#user_name_output").hide();
        $("#go").click(function() {
          alert('You clicked me!');
        });
      });
    </script>
  </head>
  <body>
    <p>
      Please type your name below and click the button.
<input type="text" id="user_name_input"> <button type="button" id="go">Go!</button> </p> <h1 id="user_name_output"></h1> </body> </html>

Figure 1. Starting “Hello world!”

Line 19 creates a text input field. Line 20 creates a button right next to it. Line 22 gives a place for output.

The code in lines 9 to 12 is run when the page is ready. Line 9 hides the output area. Line 10 sets up an event handler, run when the user clicks the button.

So far, so good. Let’s add the rest of the code. When the user clicks the button, what we want to happen is this:

  • Get whatever the user typed.
  • Put it in the output area.
  • Show the output area.

Here’s some code:

$("#go").click(function() {
  //Get the user's name.
  user_name = $("#user_name_input").val();
  //Add it to the output.
  $("#user_name_output").text("Hello " + user_name + "!");
  //Show the output.
  $("#user_name_output").show('slow');
});

Figure 2. Code

Please try it.

Lines 2, 4, and 6 are comments. Any line in your JavaScript that starts with // is ignored by your browser. The comments help explain what the code is doing.

Adding comments is good practice. When someone needs to change what the code on the page does, s/he will first read the comments to figure out how the current code works. Good comments make that task easier.

Line 3 gets whatever the user typed. $("#user_name_input").val() finds the field with the id of user_name_input, and gets its contents. val() is an attribute of form fields. It returns the contents of the field.

What does line 3 do with the value? It puts it in a variable.

user_name = $("#user_name_input").val();

A variable is a temporary holding place in the computer’s memory. When the browser sees user_name for the first time, it grabs some memory and labels it user_name.

The = in line 3 says “Take the value on the right, and put it into the variable on the left.” So line 3 takes the value in the text field, and stores it in the variable user_name.

Look at line 5:

$("#user_name_output").text("Hello " + user_name + "!");

"Hello " + user_name + "!" says to take the text “Hello “, put the contents of the variable user_name on the end, and then put the text “!” on the end of that.

Huh!?

Let’s take a side trip, to see how this works.

Variables and constants

user_name = "Tim";
alert("user_name");
alert(user_name);
alert("user_name: " + user_name);
alert(user_name + "Taylor");

Figure 3. Variables and constants

Line 1 shows the difference between variables and constants. user_name is a variable. As just explained, a variable is a temporary storage place in the computer’s memory for some data. You can put data into it, like Tim, or Lenny, or Katherine.

"Tim" is a constant. It will always be, well, "Tim". The quotes ("") are JavaScript’s way of representing fixed text.

Line 2 is:

alert("user_name");

It outputs a constant. "user_name" is a fixed value that will never change. This does not refer to the variable user_name. "user_name" means the exact text "user_name", just as "Renata likes treats" refers to the exact text "Renata likes treats".

On the other hand, line 3 outputs the contents of the variable user_name.

alert(user_name);

The line doesn’t have quotes around user_name. The browser says to itself, “Self, user_name must be a variable. I’ll get its value from memory, and show whatever that value is.”

Here’s a picture of these two lines in action.

A variable and a constant

Figure 4. A variable and a constant

The first line outputs whatever is between the quotes exactly as is. The second line fetches the contents of the variable user_name from memory, and outputs that.

Here’s Figure 3 again.

user_name = "Tim";
alert("user_name");
alert(user_name);
alert("user_name: " + user_name);
alert(user_name + " Taylor");

Figure 3 (again). Variables and constants

Let’s look at line 4. It takes the exact text user_name: (with a colon and a space at the end), appends the contents of the variable user_name, and outputs that.

Appending a constant and a variable

Figure 5. Appending a constant and a variable

Line 5 takes the contents of variable user_name and appends Taylor. So it outputs Tim Taylor.

Tim Taylor

Figure 6. Tim Taylor

Got it? A variable is a piece of memory with a name. A constant is a fixed value. Text constants – often called string constants – have quotes around them. Single quotes will also work, like ‘CC’.

Back to “Hello world!”

Here’s the “Hello world!” program again.

$("#go").click(function() {
  //Get the user's name.
  user_name = $("#user_name_input").val();
  //Add it to the output.
  $("#user_name_output").text("Hello " + user_name + "!");
  //Show the output.
  $("#user_name_output").show('slow');
});

Figure 2 (again). Code

So, in line 5, "Hello " + user_name + "!" tells the browser to take the constant “Hello “, append the contents of the variable user_name, and append the constant “!”.

If user_name has Renata in it, the result would be Hello Renata! If user_name has Larry the crazy pickle in it, the result would be Hello Larry the crazy pickle!

What happens to that text? It’s inserted into the element with the id of user_name_output.

Don’t forget the #s in all of this. The code won’t work without them. Computers are picky.

Finally, line 7 shows the element with the id of user_name_output.

Exercise: First and last name

Try this page, but don’t look at the source code. See if you can reproduce it.

Hint: Start by copying the “Hello world!” code, and making another text field.

Upload your solution to your server. Add the URL below.

(Log in to enter your solution to this exercise.)

What now?

On this page, you learned how to get some data from the user and show it. Let’s make a small change to improve a form’s usability.


How to...

Lessons

User login

Log in problems? Try here


Dogs