Skip to main content

Ivan Teoh

Something personal yet public

174-homework4.html

(Source)

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>JavaScript 101</title>
    <script type="text/javascript">

    function createFieldset(id, parent){
        var element = document.createElement('fieldset');
        element.setAttribute('id', id);
        parent.appendChild(element);
        return element;
    }

    function createInput(id, parent){
        var element = document.createElement('input');
        element.setAttribute('id', id);
        element.setAttribute('type', 'text');
        parent.appendChild(element);
        return element;
    }

    function createButton(id, parent, name, funcName) {
        var element = document.createElement('input');
        element.setAttribute('id', id);
        element.setAttribute('type', 'button');
        element.setAttribute('value', name);
        element.setAttribute('onclick', funcName);
        parent.appendChild(element);
        return element;
    }

    function createSpan(id, parent, text){
        var element = document.createElement('span');
        element.setAttribute('id', id);
        var child = document.createTextNode(text);
        element.appendChild(child);
        parent.appendChild(element);
        return element;
    }

    function adding(){
        var total = parseInt(document.getElementById('total').value);
        if (total && total < 11 && total > 1) {
            var grandTotal = 0;
            for (var i = 0; i < total; i++) {
                    var number = document.getElementById('input' + i);
                    if (!number) {
                        continue;
                    }
                    var numberValue = parseInt(number.value);
                    if (numberValue) {
                        grandTotal += numberValue;
                    } else {
                        alert('"' + number.value + '" is not an integer');
                    }
            }
            var result = createFieldset('result', document.body);
            createSpan('span', result, grandTotal);
        } else {
            alert('Have you changed the total?');
        }
    }

    function submit(){
        var total = parseInt(document.getElementById('total').value);
        if (total && total < 11 && total > 1) {
            var fieldset = createFieldset('fieldsetlists', document.body);
            for (var i = 0; i < total; i++) {
                createInput('input' + i, fieldset);
            }
            createButton('addButton', fieldset, 'add', 'adding();');
        } else {
            alert('Please enter a number between 2 to 10!');
        }
    }
    </script>
</head>
<body>
<fieldset>
    <p>How many numbers do you want to add (max is 10)</p>
    <input type='text' id='total' />
    <input type='button' value='submit' onclick='submit();'/>
</fieldset>
</body>
</html>