Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

290 CHAPTER 6 Essential JavaScript and jQuery


In Figure 6-11, notice there is an array element (shown as [0]), and the length property is
set to 1. This is how you can verify the result of the query. Element 0 is a direct reference to
the txtInput DOM element.
When you run the test, it will pass but not for the correct reason; txtInput and txtResult
reference the jQuery wrapper, not the actual DOM element. When the value property is set
to ‘0’, a new property is dynamically created on the jQuery object and set to ‘0’. However, the
intent of this query is to set the text box value to ‘0’. To correct this problem, you can use the
val method on the jQuery object. The val method gets or sets the value property of a form
control that has a value property. The following is the modified test code.
module('QUnit Test Suite', { setup: function () { initialize(); } });

test("Initialize Test", function () {
expect(2);
var expected = '0';
equal(txtInput.val(), expected, 'Expected value: ' + expected +
' Actual value: ' + txtInput.val());
equal(txtResult.val(), expected, 'Expected value: ' + expected +
' Actual value: ' + txtResult.val());
});

After the four changes are made to the test, running the test shows that test assertions fail
because value properties on the DOM elements are not being set. To fix the problem, modify
the code in the clear function to set the value by using jQuery’s val method. The following is
the completed code.
var txtInput;
var txtResult;

function initialize() {
txtInput = $('#txtInput');
txtResult = $('#txtResult');
clear();
}

function clear() {
txtInput.val('0');
txtResult.val('0');
}

IMPORTANT REFRESH YOUR SCREEN
HTML documents and JavaScript files are normally cached by the browser, so you might
not see changes you made by just running the webpage. To refresh, press Ctrl+F5 after the
screen is displayed.

This code is complete, the tests pass, and the text boxes are populated with ‘0’. It’s impor-
tant for you to use the jQuery object whenever possible so you can benefit from the cross
Free download pdf