Search code examples
javascriptjqueryfunctioncallbackchaining

jQuery chaining functions task


I'd like to use jQuery to build a series of six buttons with values A, B, C, 1, 2, 3. Each time the user clicks a button, its value is appended to a text field. However, the user must not be able to add two letters or two numbers in a row. Thus, if A, B, or C is pressed, only the numbers should work, and vice-versa.


Solution

  • This should do it:

    function createButton(target, val, fn) {
        var btn = document.createElement("button");
        btn.value = val;
        btn.onclick = function() {
            fn(val);
        };
        target.appendChild(btn);
    }
    
    var state = null,
        values = [];
    function addLetter(l) {
        if (state == "letter") return false;
        state = "letter";
        values.push(l);
        update();
    }
    function addNumber(n) {
        if (state == "number") return false;
        state = "number";
        values.push(n);
        update();
    }
    
    createButton(inputs, "A", addLetter);
    createButton(inputs, "B", addLetter);
    createButton(inputs, "C", addLetter);
    createButton(inputs, 1, addNumber);
    createButton(inputs, 2, addNumber);
    createButton(inputs, 3, addNumber);
    
    function update() {
        // do something with values
    }
    

    Demo at jsfiddle.net