JavaScript – Processing URL and Query String

Processing URL and Query String

Prerequisites

Lecture – Form Validation in Javascript

Summary

Topics covered:

Using the location object

Processing form input

Video

Reference Materials

HTMLForm.html

<!DOCTYPE html>
<html>
  <head>
    <title>HTML 5 Form</title>
    <link rel="stylesheet" type="text/css" href="/styles.css">
<script>
 function validateForm()
 {
    var fname = document.forms["myForm"]["name"].value;
    return validateNotBlank(fname, "Name");
 }
 
 function validateNotBlank(value, label)
 {
   if (value==null || value=="")
     {
     alert("Please enter a value for " + label);
     return false;
     }
  return true;     
 }
</script>
  </head>
  <body>

<form name="myForm" onsubmit="return validateForm()" action="HTMLFormRequest.html" >
<p>
<label>Enter Name (Javascript): <input type="text" name="name"></label><br/>
<label>Color(HTML5): <input type="color" name="color"/></label><br/> 
<label>Date HTML5): <input type="date" name="date" /></label><br/>
<label>E-Mail(HTML5): <input type="email" placeholder="name@domain.com" name="email" /></label><br/>
<label>Number(HTML5): <input type="number" min="0" max="10" name="number"/></label><br/>
<label>Range(HTML5): <input type="range" min="0" max="10" value="5" name="range"/></label><br/>
</p>
<input type="submit" value="Submit" />
</form>
  </body>
</html> 

HTMLFormRequest.html

<!DOCTYPE html>
<html>
  <head>
    <title>HTML 5 Form Process</title>
    <link rel="stylesheet" type="text/css" href="/styles.css">
<script>
function setup()
{
  document.writeln("<p> location: " + location + "</p>");
  document.writeln("<p> location.search: " + location.search + "</p>");
  document.writeln("<p> location.search (URI Decoded): " + decodeURIComponent(location.search) + "</p>");
  var sl = location.search.split("&");
  document.writeln("<p> split string: " + sl + "</p>");
  document.writeln("<p> First element: " + sl[0] + "</p>");
  document.writeln("<p> Length: " + sl.length + "</p>");
  var split1=sl[0].split("=");
  document.writeln("<p> First element Name: " + split1[0] + "</p>");
  document.writeln("<p> First element Value: " + split1[1] + "</p>");
}
</script>
  </head>
  <body onload="setup();">
  </body>
</html>

Additional Information

JavaScript location object – http://www.w3schools.com/jsref/obj_location.asp

JavaScript split method – http://www.w3schools.com/jsref/jsref_split.asp

COP 4813 Lectures