Tag Archives: input

Moving the player in a 2D game with Unity and C# code

This video explains how to move your player in a 2D game in Unity with C# code. After watching this video, you will be able to move your player left and right in a scene using keyboard input.

Watch the video below and scroll down to see the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
  }
  
  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }
  }
}

Next tutorial: Making the player jump with C# code

Adding radio buttons to an Android app with Xamarin

This tutorial explains how to add radio buttons to an Android app and make decisions based on which option the user selects. Radio buttons allow the user to select one item from a list of items. This is what an app screen with radio buttons looks like:

image10

Step 1

To get started, create a new Android app solution in Xamarin and then open the Main.axml file (in the Resources > layout folder). Drag a Text (Medium) element and three RadioButton elements from the Toolbox on to the app screen. Change the Text values on each element from the Properties panel and make sure each radio button has a name (eg. radioButton1, radioButton2, radioButton3) after @+id/ in the Id field on the Properties panel.

image1

Step 2

Add a Space element and another Text (Medium) element to your screen. Resize the Space element to make some space between the radio buttons and the Text (Medium) element. Give the Text (Medium) element a name eg @+id/resultTextView.

image2

Step 3

Open the MainActivity.cs file and define the three radio buttons and the text view. Then add them to the OnCreate method, so they can be accessed by the code.

image3

Step 4 

Now add a click event for each radio button so that the app displays a message saying which option was selected.

image4

Save your code and test the app. The example shown below is what you should see. However, the problem is that once you select an option it can’t be de-selected. Also, when using radio buttons you should only be able to select one option at a time but at the moment you can have more than one option selected at a time. We will fix this in the next section.

image5

Step 5

Go back to the screen design and delete all three radio buttons. Replace these radio buttons with a RadioGroup from the toolbox. This RadioGroup element has the name @+id/radioGroup1 . You will notice that the RadioGroup provides you already with three radio buttons grouped together. A RadioGroup can have any amount of radio buttons in it, but only one can be selected at a time.

image6

If you go to the Source view you can see that you can add more RadioButton elements to belong to the RadioGroup as long as you add them inside the RadioGroup tags.

image7

Change the Text value on each RadioButton so they are different.

image8

Step 6

Save the Main.axml file and go back to the MainActivity.cs file. The code needs to be changed so now it can access the RadioGroup element. A CheckChanged event is also added to detect when an option has been checked by the user. When this event fires, the option they selected is store in the option variable and the result is displayed to the user.

image9

Now if you test your app, it should look like what you see below. You could now add if statements to check which radio button was selected and have another event occur.

image10

Ignore or strip HTML tags from strings in PHP

This tutorial explains how to use the htmlentities and strip_tags functions in PHP to ignore or strip HTML tags in strings. You may want to do this if you are allowing users to enter data into a form element such as a text box and don’t want the user to be able to mess up the display of your website by adding HTML tags to data.

The first function called htmlentities, is used to ignore HTML tags in strings. The second function called strip_tags is used to completely remove the HTML tags from a string. Watch the video below to see how you can protect your website or web app using these functions with forms and then scroll down to see the sample code.

Sample PHP code:

<!DOCTYPE html>
<html>
<head>
  <title>HTML entities and strip tags</title>
</head>

<body>
  <?php
    if(isset($_GET['string1'])){
      echo "Using htmlentities function: " , htmlentities($_GET['string2']), "<br/>";
      // htmlentities displays HTML tags as they are
    }

    if(isset($_GET['string2'])){
      echo "Using strip_tags function: " , strip_tags($_GET['string2']), "<br/>";
      // strip_tags will strip the HTML tags
    }
  ?>
  <h3>Enter your name below:</h3>
  <form action="" method="GET">
    First string (using htmlentities): <input type="text" name="string1"><br/>
    Second string (using strip_tags): <input type="text" name="string2"><br/>
    <input type="submit">
  </form>
</body>
</html>

Select lists and PHP

Select lists, which are created in HTML code, can be useful when a user needs to select one or more items from a list of different items. This tutorial explains how to add a select list to a form in a web page using some simple HTML code and then how to use PHP code to use the submitted data from the form.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

There are two files used in this tutorial: form.php which creates a select list and collects the user input, and action_handler.php which uses and processes the submitted data.

Here is the code for the form.php file:

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Which countries would you like to visit?</p>
    <select multiple name="countries[]" style="width:100px;">
      <option value="France">France</option>
      <option value="Brazil">Brazil</option>
      <option value="India">India</option>
      <option value="Japan">Japan</option>
    </select>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Here is the code for the action_handler.php file:

<?php
  if(isset($_POST['countries'])){
    $countries = $_POST['countries'];
    echo "You selected the following countries:<br/>";
    foreach($countries as $key => $value){
      echo "$value<br/>";
    }
  }
  else{
    echo "You must select at least one country.";
  }
?>

Handling form data with PHP

In this tutorial you will finally get to work with real user input through the use of forms and PHP code. This tutorial will show you how to create a simple PHP form which will ask for the user’s name and then display a simple message back to the user. This is what the form will look like:

Form with text box user input .
Form with text box user input .

The PHP code also includes some basic data validation that checks that the user has entered some value and asks them to enter their name if they haven’t.

Watch the video below and then scroll down to see the sample code.

Sample code

There are two files required – an HTML or PHP file which contains the form (eg. form.php), and a PHP file which handles the form data (eg. form_handler.php).

Step 1 – Create a form.php file and add the following code.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <h3>Enter your name below:</h3>
  <form action="action_handler.php" method="GET">
    <p>Name: <input type="text" name="name"> <input type="submit"></p>
  </form>
</body>
</html>

Step 2 – Create an action_handler.php file and add the following code. The empty function is used to check if a text box has been left empty by the user (if they haven’t entered a value in the text box). Make sure both files are in the same folder/directory.

<?php
  $name = $_GET['name'];
  if(empty($name)){
    echo "You must enter your name.";
  }
  else{
    echo "Hello there, $name.";
  }
?>

That’s it. Now open the form.php file in your browser and try it out!

Moving an object with force in PlayCanvas

This tutorial explains how to use keyboard input to move an object around. But rather than telling the object how far it needs to move (like in this other tutorial), we will apply force to the object instead. This means that the object your moving can also hit other objects and interact with them rather than just going through them.

Step 1 – Setting up the object you want to move

To begin with, you need to create an object or use a model that you want to move. Then you need to add a Rigid Body component and a Collision component so that this object can collide and interact with other objects in the scene. For this example, I have added a Box entity (click + in the Hierarchy and then click Box) but you can use another 3D shape or model.

3dobject
Then you need to select the object and click on Add Component (in the Inspector panel on the left side of the screen) and choose the Collision component. If you have a box shape (entity) then you should set the Collision Type to Box (if you have a sphere shape, then select Sphere for Type, and so on).

Match your collision settings up so they look like the settings shown below. The numbers in the Half Extents property boxes should be half the numbers in the Scale property boxes above it. Eg. if the scale X property of the box has a value of 4 then the Half Extents X value should be 2.

box_collision

Now click on Add Component again and this time add the Rigid Body component. Change the Type to Dynamic and modify the values so they are the same as those below (experiment with these values later to get the effect you want).

rigid_body
It is important to make sure any other objects that this object will interact with also have Rigid Body and Collision components attached to them. For example, if you don’t want this object to fall through your ground in the scene, then the ground object should have a Static type Rigid Body and a Collision component.

If you want other objects to not be moved by this object, they should have a Static type Rigid Body and Collision component. Otherwise, if you want this object to move other objects when it touches them, add Dynamic type Rigid Body and Collision components to those other objects.

Adding a script to the object

Click on + in the Assets panel and choose Script to create a new script.

create_script
Call the new script moveWithForce.js and hit Enter to create the script.

script_name

Now you need to attach the script to the 3D object or model you want to move or control. Select the 3D object (eg. box) and then click on Add Component and select Script. Drag the moveWithForce.js script onto the Scripts component on the object in the Inspector panel and then let go. The script should now be attached to the object.

script_attached

 

Writing the code

Double-click on the moveWithForce.js script you just created in the Assets panel and replace all of the existing code with the following code in the Code Editor window:

// Add this code to any object you want to move with force
// Object that this script is attached to must have collision component and DYNAMIC rigid body component

pc.script.attribute("power", "number", 1000);  // set power to initial value of 1000
pc.script.create('moveWithForce', function (app) {
    // create force variable
    var force = new pc.Vec3();
    // Creates a new MoveWithForce instance
    var MoveWithForce = function (entity) {
        this.entity = entity;
    };

    MoveWithForce.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            // Check for required components
            if (!this.entity.collision) {
                console.error("First Person Movement script needs to have a 'collision' component");
            }
            
            if (!this.entity.rigidbody || this.entity.rigidbody.type !== pc.BODYTYPE_DYNAMIC) {
                console.error("First Person Movement script needs to have a DYNAMIC 'rigidbody' component");
            }
            
            // Listen for keyboard press events
            app.keyboard.on(pc.EVENT_KEYDOWN, this._onKeyDown, this);
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {

            // movement
            var x = 0;
            var z = 0;
            var y = 0;
            
            // Use W-A-S-D keys to move player around and Space to make player jump
            // Check for key presses
            if (app.keyboard.isPressed(pc.KEY_LEFT)) {
                x -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_RIGHT)) {
                x += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_UP)) {
                z -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_DOWN)) {
                z += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_SPACE)) {
                console.log("space pressed");
                y += 0.05;
            }
            
            // use direction from keypresses to apply a force to the character (x and z axes)
            if (z !== 0) {
                force.set(0, 0, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            if (x !== 0) {
                force.set(x, 0, 0).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            // use direction from keypresses to apply a force to the character (y axis)
            if (y !== 0) {
                force.set(x, y, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
        },
        
        _onKeyDown: function (event) {
            // When the space bar is pressed this scrolls the window.
            // Calling preventDefault() on the original browser event stops this.
            event.event.preventDefault();
            console.log("Scrolling disabled");
        }
    };

    return MoveWithForce;
});

Now click on Save and then go back to the game Editor window. That’s it! Launch your game by clicking on the Launch (play) button and you should now be able to control the 3D object/model by using the keyboard to move it around and make it jump. The code is set up to move the object using the arrow keys and space bar to jump. However, you can change these keys and you can also remove the code that makes the object jump if you don’t want to make it jump in the game.

 

 

 

Moving objects with keyboard input in PlayCanvas

If you watched the previous tutorial you would have learned how to make an object move on its own using JavaScript code. In this tutorial, we will make an object move around using keyboard input. That is, if the left arrow key is pressed on the keyboard then we can make the object move left. If the right arrow key is pressed on the keyboard then we can make the object move right, and so on…

Keyboard input will be very useful in your games eg. to make a player jump, to move around, pick up objects or enter your name in the high score book! Watch the video to find out how to add keyboard input to your games and then try out the sample code further down the page.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script.

In the code, you will see app.keyboard.isPressed – this will check if the key is being pressed during the current frame. If you hold down the key, the object will keep moving. If you use another method called app.keyboard.wasPressed instead it will only check if the key was pressed in the current frame (it will detect one keypress and won’t keep the object moving when you hold the key down).

pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 if(app.keyboard.isPressed(pc.input.KEY_RIGHT)){
 this.entity.translateLocal(0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_LEFT)){
 this.entity.translateLocal(-0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_UP)){
 this.entity.translateLocal(0,0.1,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_DOWN)){
 this.entity.translateLocal(0,-0.1,0);
 }
 }
 };
 
 return Move;
});

Mouse input in Unity

This tutorial explains how to detect mouse button clicks and mouse movement in your game using a C# script. This will allow your players to interact with the game using their mouse.

Watch the video below and then scroll down to see the sample code.

Mouse button clicks

To detect mouse button clicks, you use the GetMouseButtonDown() method which takes an integer value (between 0 and 2) to specify which mouse button you want to check. 0 is for the left button, 1 is for the right button, and 2 is for the middle button. The method will return a Boolean value indicating whether the specified mouse button has been pressed when using code like the example shown below.

bool isLeftButtonDown = Input.GetMouseButtonDown(0);
bool isRightButtonDown = Input.GetMouseButtonDown(1);
bool isMiddleButtonDown = Input.GetMouseButtonDown(2);

This code will display a message if the left mouse button is pressed:

if(Input.GetMouseButtonDown(0))
{
 print("The left mouse button was pressed");
}

Save the script and then run the scene. Check the output in the console when you click the left mouse button.

Mouse movement

Mouse movement is measured by reading the amount that the mouse has moved since the last frame, across the X and Y axes on screen.

The sample code below will read the mouse movement and display the value in the console. Place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float mouseXValue = Input.GetAxis("Mouse X");
float mouseYValue = Input.GetAxis("Mouse Y");
 
if(mouseXValue != 0)
{
 print("Mouse X movement: " + mouseXValue);
{
 
if(mouseYValue != 0)
{
 print("Mouse Y movement: " + mouseYValue);
{

Save the script and then run the scene. Check the output in the console when you move the mouse around the screen.

Transforming objects using scripts

This video tutorial will show you how to transform objects (move, rotate, scale) in your Unity game using C# scripts and also how to implement player interaction with the game by allowing players to transform objects using keypresses on their keyboard.

Watch the video below and then scroll down to see the sample code.

Here is some sample code with different object transformations assigned to different keypresses on the keyboard. You can change the transformations and assigned keys although it is a good idea to use the input manager rather than specific keypress detection so that your players have the option of remapping keys to suit their own preferences.

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 if (Input.GetKey (KeyCode.W)) {
 transform.Translate (0f,0f,0.1f);
 }
 if (Input.GetKey (KeyCode.S)) {
 transform.Translate (0f,0f,-0.1f);
 }
 
 if (Input.GetKey (KeyCode.D)) {
 transform.Translate (0.1f,0f,0f);
 }
 if (Input.GetKey (KeyCode.A)) {
 transform.Translate (-0.1f,0f,0f);
 }
 
 if (Input.GetKey (KeyCode.Z)) {
 transform.Rotate (0f,1f,0f);
 }
 
 if (Input.GetKey (KeyCode.X)) {
 transform.Rotate (0f,-1f,0f);
 }
 
 if (Input.GetKey (KeyCode.C)) {
 transform.localScale = new Vector3(1f,1f,1f);
 }
 
 if (Input.GetKey (KeyCode.V)) {
 transform.localScale = new Vector3(5f,5f,5f);
 }
 
 }
}

Note: If you find that the values for x, y and z axes seem to work the opposite to what you expect, it might be because you have the camera at a different angle. For example, if your camera is on the opposite side of your object, then pressing the key that is meant to move the object left might actually move it to the right.

Now try using variables to store the values for speed, eg:

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 public float turnSpeed = 5.0f;
 public float forwardSpeed = 0.25f;
 
 // Update is called once per frame
 void Update () {
 transform.Rotate(turnSpeed, 0.0f, 0.0f);
 transform.Translate(0.0f, 0.0f, forwardSpeed);
 }
}

Here is another method of moving objects on their own at a steady speed (this example does not include keyboard input).

using UnityEngine;
using System.Collections;
 
public class moveCube : MonoBehaviour {
 
 public float speed = 1.0f;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 transform.Translate (Vector3.forward * speed * Time.deltaTime);
 // This will move the cube forward on its own at steady speed
 // Vector3 is for 3D , Vector2 is for 2D
 // You can change Vector3.forward to Vector3.back, Vector3.left, or Vector3.right
 
 
 }
}

Keyboard input in Unity

In Unity, you can set up your game to detect specific keypresses and then react to those keypresses. However, there is a better way of setting up input using Unity’s built-in Input Manager.

The video below will show how to use the Input Manager and how to also detect specific keypresses in your game. After you’ve finished watching the video, scroll down to see the sample code.

Input Manager

Setting up your game to detect specific keypresses doesn’t allow players to remap the game input controls to suit their preferences. However, if you use the Input Manager you can allow the player to map the controls to their own liking or use the defaults (eg. the W, A, S and D keys).

You can set up controls for each of the different axes in the Input Manager by clicking Edit > Project Settings > Input. Then you can write a script using the GetAxis() method to detect key presses.

Below is some sample code that will display horizontal and vertical movement in the console when the W, A, S and D keys (or arrow keys) are pressed. Simply place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float horizontalValue = Input.GetAxis("Horizontal");
float verticalValue = Input.GetAxis("Vertical");
 
if (horizontalValue != 0)
{
 print("Horizontal movement: " + horizontalValue);
}
 
if(verticalValue != 0)
{
 print("Vertical movement: " + verticalValue);
}

Save the script and then run the scene. Check the output in the console after pressing the W, A, S and D keys and the arrow keys.

Try out the code above and see what happens when you press the W, A, S and D keys or arrows keys on your keyboard. Also, did you notice how the sentences and values are combined in the print statements above? This is an example of concatenation (where strings are joined together).

Specific key input

Although it is generally a good idea to use the Input Manager for key input detection, it may sometimes be necessary to check whether a specific key has been pressed by the user. To do this, you can use the GetKey() method. This method will read a keycode which corresponds to a specific key on the keyboard. It will then return either a true or false value depending on whether the key is pressed or not.

As an example, to check if the A key is being pressed, you can use the following code. Just place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

bool isKeyDown = Input.GetKey(KeyCode.A);

Tip: In MonoDevelop, if you are not sure what keycode corresponds to a key, you can begin typing in the name of the KeyCode object followed by a period. A popup menu should appear, showing you all of the possible choices. This automatic popup feature in MonoDevelop can be used for many other objects/methods too and is pretty handy.

You can use a simple if statement to specify an action to occur when a keypress is detected. For example, the following code will output a message to the console saying that the ‘A’ key has been pressed when it is detected that the ‘A’ key has been pressed.

if(Input.GetKey(KeyCode.A))
{
 print("You pressed the 'A' key.");
}

Save the script and then run the scene. Check the output in the console after pressing the ‘A’ key.

Treating text input from a form as an integer or float

If you have completed the User Input with Forms tutorial, you will now know how to ask the user for text input through a form, and use that input in some way. However, if you trying collecting input from the user in the form of numbers and then try to do some logical operations on those numbers, you may run into problems.

The first problem is that any text input will be treated as a string, not an integer. So if you try to compare two numbers eg. check if the inputted number is equal to 5, JavaScript will be trying to check if a string input is equal to a number and will not be checking if an integer input is equal to a specific integer.

The video and sample code below shows an example of using parseInt() to treat text input from a textbox as an integer value. You can also use parseFloat() to parse a string as a float (real number with decimal places). The video also shows how to grab the value from a textbox by using document.getElementById(‘idname’).value so that a logical operation can happen

The example used in the video and the code below is a simple math question game. The program displays a math problem to the user. The user can enter their answer in a textbox and the page will display a message if the user gets the correct answer. Watch the video below to see how to write the code for this program.

Once you have completed the tutorial, your program should work like this:

MathGame

Here is the code for the program:

<html>
<head>
<title>Simple math game</title>
<script type="text/javascript">
var answer = 15; // this is the answer to the math question
var attempt; // the user's attempt will be stored in this variable
 
function guess(){
 attempt = document.getElementById('attempt').value;
 attempt = parseInt(attempt); // this will now treat the textbox input value as an integer
 var result = document.getElementById('result');
 
 if (attempt == answer){
 result.innerHTML = "Correct!";
 }
 else{
 result.innerHTML = "Try again.";
 }
 
}
 
</script>
</head>
<body>
 <p>What is the answer to 10+5?</p>
 <form>
 Enter your answer:<input type="text" id="attempt"/><br/>
 <input type="button" value="Submit" onclick="guess();"/>
 </form>
 <p id="result">Enter your answer in the textbox above. It must be a number only.</p>
 
 
</form>
</body>
</html>

 Next tutorial: Submitting forms

JavaScript prompts (input boxes)

A prompt (or input box) is a popup box which asks the user a question and allows them to type and submit their answer in a textbox. The user must enter a value in the textbox or click on OK/cancel before they can continue interacting with the webpage.

These prompts can be intrusive and annoying so only use them when absolutely necessary. Forms are a better way of getting user input. The only data validation being used in this example is checking whether the input text box is empty or not.

Watch the video below and then scroll down to see the sample code.

Here is the code for the prompt box:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript Prompt Box</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is a prompt box which asks for a name
 // The name is then displayed in the browser (only if a name is entered)
 
 var name=prompt("Please enter your name","Enter name here");
 if (name!=null) // this means if the name is NOT empty
 {
 message="Hello " + name + "! How are you today?";
 document.write(message);
 } 
 
 </script>
 
</body
</html>

Here are some questions to consider after using the sample code:

  • What happens when the user clicks on OK before replacing the default value with their own text value? Can this be changed?
  • What will be displayed in the message if the user clicks on Cancel? How can this be changed?
  • Can you think of a better way of asking the user a question and using their input, rather than using a JavaScript prompt?

Next tutorial: Using the HTML5 canvas tag to draw shapes

Checkboxes and form validation

This video tutorial explains how to implement checkboxes in an HTML form and how to use JavaScript to validate the form data by checking whether at least one option has been selected. Remember, radio buttons are used when you want the user to select only one option or answer to a question, and checkboxes are used when you wish to allow the user to select more than one option (if more than one option is available).

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Checkboxes</title>
 <script type="text/javascript">
 
 function isChecked(){
 var India = document.getElementById('India').checked;
 var France = document.getElementById('France').checked;
 var Japan = document.getElementById('Japan').checked;
 var Sweden = document.getElementById('Sweden').checked;
 
 if(India==false && France == false && Japan==false && Sweden==false){
 alert('Please select a country!');
 return false;
 }
 else{
 return true;
 }
 }
 
 </script>
 
</head>
<body>
<form action="submission.html" method="get" onsubmit="return isChecked();">
 <p>Which countries would you like to visit most?</p>
 <input type="checkbox" name="countries" value="India" id="India"/>India <br/>
 <input type="checkbox" name="countries" value="France" id="France"/>France<br/>
 <input type="checkbox" name="countries" value="Japan" id="Japan"/>Japan<br/>
 <input type="checkbox" name="countries" value="Sweden" id="Sweden"/>Sweden<br/>
 <input type="submit" value="Submit"/>
</form>
 
</body>
</html>

Next tutorial: Alert boxes and confirmation boxes

User input with forms

We will now start using forms to take user input. Forms include elements such as input text boxes, checkboxes, radio buttons, drop-down lists, and submit buttons.

In this tutorial, we will ask the user to enter their name and then display a personalised welcome message with their name included. In the first example, we will do do just that. In the second example, we will also hide the form once the user has entered and submitted their name.

Watch the video below and then scroll down to see the code.

Here is the code for the first example, where we ask for the user’s name and display a personalised welcome message. Notice that the form still remains after it has been submitted.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form>
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

In the second example (below), once the user has entered their name and clicked on the ‘Submit’ button, the personalised message will be displayed and the form will also disappear.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 var formContent = document.getElementById('entername');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 formContent.innerHTML = ""; // this removes the form text input box after name has been entered.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form id="entername">
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

Next tutorial: Treating text input from a form as an integer of float