jQuery allows developers to easily process user input and then update the page to reflect this input. The previous recipes of this chapter have looked at detecting changes on input values and clicks on various page elements. This recipe will help you to create a web page that will update a header element based on the title that has been selected from a drop-down menu.
Getting ready
Create a blank HTML document named recipe-4.html, with the latest version of the jQuery library downloaded and ready for use.
How to do it…
Using techniques similar to those you have learned in the previous recipes, perform the following steps to make changes to the DOM based on user interaction:
Add the following HTML code to recipe-4.html, which you have just created; don't forget to update the reference to the jQuery library. This HTML creates a basic HTML web page with a drop-down menu element, allowing the user to choose a number of titles. There is also a header element that we can manipulate with jQuery based on user selection.
Add the following JavaScript code within the script tags to attach a change event handler to the select input #title:
$(function(){
$('#title').change(function(){
var titleText = "";
switch ($(this).val()) {
case "1":
titleText = "This is the text for title 1";
break;
case "2":
titleText = "This is the text for title 2";
break;
case "3":
titleText = "This is the text for title 3";
break;
default:
titleText = "No Title";
}
$('#main-title').html(titleText);
});
});
Running this web page in a browser and selecting a new option from the drop-down menu will update the text of the header accordingly.
How it works…
First, we instruct jQuery to attach a change event handler to the #title select input using the following code:
When the user changes the selected option in the drop-down input, the change event handler is executed.
In the function argument, we can use $(this) to refer to the #title select input and then use $(this).val(); to get its selected value. Once we have this value, we can perform any action we require using JavaScript. In this example, we determine which title has been selected using a JavaScript switch statement, as shown in the following code snippet:
var titleText = "";
switch ($(this).val()) {
case "1":
titleText = "This is the text for title 1";
break;
case "2":
titleText = "This is the text for title 2";
break;
case "3":
titleText = "This is the text for title 3";
break;
default:
titleText = "No Title";
}
Depending on the selected title value, we create some text which we then provide to $('#main-title').html();. This will update the #main-title header element's HTML to be the provided text.
This illustrates a very simple task of how a jQuery developer can process user input and perform an action to alter the page.