Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 3 129


function plusClick() {
txtResult.value = Number(txtResult.value) + Number(txtInput.value);
}


  1. Press F5 to run the test, which should pass.
    When btnMinus is clicked, the value in txtInput will be subtracted from the value in
    txtResult.

  2. In the tests.js file, add a new test to check btnMinus when it’s clicked.
    Your test code should look like the following:
    test("Subtract Test", function () {
    expect(1);
    txtInput.value = '10';
    txtResult.value = '20';
    var btnMinus = document.getElementById('btnMinus');
    QUnit.triggerEvent(btnMinus, "click");
    var expected = '10';
    equal(txtResult.value, expected, 'Expected value: ' + expected +
    ' Actual value: ' + txtResult.value);
    });

  3. Press F5 to run the test and verify that the test fails because you haven’t subscribed to
    the click event of btnMinus.

  4. In the initialize function, add code to subscribe to btnMinus and call the minusClick
    function. Add the minusClick function with code to subtract txtInput from txtResult.
    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);
}

function minusClick() {
txtResult.value = Number(txtResult.value) - Number(txtInput.value);
}


  1. Press F5 to run the test, which should pass.
    When btnClearEntry is clicked, the value in txtInput will be set to zero.

  2. In the tests.js file, add a new test to check btnClearEntry when it’s clicked.
    Your test code should look like the following:
    test("Clear Entry Test", function () {
    expect(1);

Free download pdf