Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 3 131



  1. In the initialize function, add code to subscribe to btnClear and call the clear function.
    Add the clear function with code to reset txtInput and txtResult to zero.
    Your code should look like the following:
    function initialize() {
    for (var i = 0; i < 10; i++) {
    document.getElementById('btn'+i)
    .addEventListener('click', numberClick, false);
    }
    txtInput = document.getElementById('txtInput');
    txtResult = document.getElementById('txtResult');


document.getElementById('btnPlus')
.addEventListener('click', plusClick, false);
document.getElementById('btnMinus')
.addEventListener('click', minusClick, false);
document.getElementById('btnClearEntry')
.addEventListener('click', clearEntry, false);
document.getElementById('btnClear')
.addEventListener('click', clear, false);
}

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


  1. Press F5 to run the test, which should pass.
    After btnPlus or btnMinus is clicked and the mathematical operation is performed,
    txtInput should be reset to zero.

  2. In the tests.js file, modify the add test and the subtract test to assert that txtInput was
    reset to zero.
    Your test code should look like the following:
    test("Add Test", function () {
    expect(2);
    txtInput.value = '10';
    txtResult.value = '20';
    QUnit.triggerEvent(btnPlus, "click");
    var expected = '30';
    equal(txtResult.value, expected, 'Expected value: ' + expected +
    ' Actual value: ' + txtResult.value);
    expected = '0';
    equal(txtInput.value, expected, 'Expected value: ' + expected +
    ' Actual value: ' + txtInput.value);
    });


test("Subtract Test", function () {
expect(2);
txtInput.value = '10';
txtResult.value = '20';
QUnit.triggerEvent(btnMinus, "click");
Free download pdf