Arrays
Tags : JavaScript Intro
Arrays
We can store multiple values in an array. We can use it store strings, numbers, booleans and variables. We can even store an array within an array. These are called multi-dimensional arrays. Watch the video for a quick example.
[1, "hello", true]
var collection = [1, "hello", true]
collection[0]
// Should return 1
collection[1]
// Should return "hello"
collection[2]
// Should return true
// Arrays inside of Arrays
// Let's change the value of collection with a new type of array
collection = [1, [2, 2.2, 2.3], 3]
collection[1][0]
// Should return 2
collection[1][1]
// Should return 2.2
collection[2]
// Should return 3
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/example.css">
<script src="scripts/jquery-1.11.3.js"></script>
<script src="scripts/myscript.js"></script>
</head>
<body>
<form>
<div class="form-group">
<label for="message">Message</label>
<input type="text" class="form-control" id="message" placeholder="Message">
</div>
<div class="form-group">
<label for="from">From</label>
<input type="text" class="form-control" id="from" placeholder="From">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" placeholder="Phone">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<p>Message: <span class="message"></span> from: <span class="from"></span> Phone: <span class="phone"></span></p>
</body>
</html>
myscript.js
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var fields = ["message", "from", "phone"];
// remember these are comments and they will not run
// for (var i = 0; i < fields.length; i++){
// $("."+ fields[i]).text($("input#" + fields[i]).val());
// }
fields.forEach(function(field){
$("."+ field).text($("input#" + field).val());
})
})
})
Try the following:
- Go back to your Form with Spans that you created and try to apply arrays and a forEach loop to refactor your code.