Tags : JavaScript Intro



Forms with JS/Jquery and a little bit of Bootstrap

Forms will help us capture user input from our website in a more structured way.

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="name">Name</label>
        <input type="text" class="form-control" id="name" placeholder="Name">
      </div>
      <div class="form-group">
        <label for="phone">Phone</label>
        <input type="text" class="form-control" id="phone" placeholder="Phone">
      </div>
      <div class="form-group">
        <label for="address">Address</label>
        <input type="text" class="form-control" id="address" placeholder="Address">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <ul class="contacts"></ul> 
  </body>  
</html>

myscript.js

$(document).ready(function(){
  $("form").on("submit", function(event){
    event.preventDefault();
    console.log("submit button is working");

    var name = $("input#name").val();
    var phone = $("input#phone").val();
    var address = $("input#address").val();
    console.log(name + " - " + phone  + " - " + address);

    $("ul.contacts").prepend("<li> Name: " + name + " Phone: " + phone + " Address: " + address + "</li>");
  })
})

Try the following:

  • Create your own form that submits the places you have been to. They can be cities or countries. Add a summary of your visit for each submission.
  • Remember to add the event to the empty function for "submit" and add event.preventDefault() to prevent the form from redirecting.