jQuery rewrites page contents

Use input fields to replace text. jQuery intro example.

by Mindy McAdams

HTML

<h1>Sentence Generator</h1>
<p>This is a jQuery example. Change a word, press Tab or Return, and you will see a new sentence. Every time you change text in one of the fields, the sentence below will change.</p>

<label>Subject</label>
<input type="text" id="subject" value="The rain">
<label>Verb</label>
<input type="text" id="verb" value="falls">
<label>Object</label>
<input type="text" id="object" value="on the plains">

<p id="sentence">
  Something new will appear here soon.
</p>

<p>This example shows you how to (1) get input from the user and put it into a variable so you can use it; (2) write text dynamically onto a page without reloading it.</p>

CSS

body {
  background: #95AB63;
  font-family: sans-serif;
  margin: 10px;
}
h1 {
  margin: 0;
  color: #F6FFE0;
}
a {
    color: #00c;
}
a:hover {
    color: #00f;
    text-decoration: none;
}
input {
  display: block;
  margin-bottom: 10px;
}

JavaScript

// when subject value changes, change the text 
$('#subject').change(function() {
	s = ($('#subject').val());
	v = ($('#verb').val());
	o = ($('#object').val());
  $('#sentence').text(s + " " + v + " " + o);
});

// when verb value changes, change the text 
$('#verb').change(function() {
	s = ($('#subject').val());
	v = ($('#verb').val());
	o = ($('#object').val());
  $('#sentence').text(s + " " + v + " " + o);
});

// when object value changes, change the text 
$('#object').change(function() {
	s = ($('#subject').val());
	v = ($('#verb').val());
	o = ($('#object').val());
  $('#sentence').text(s + " " + v + " " + o);
});