Pergunta

I have a sudoku puzzle (Click Here) and it works just fine except that I want to show the "Check My Answer" button after they have filled in all the empty cells. Is there a way to do that?

Here is my puzzle generating function and my check filled out function:

// Check if filled out
function checkFilledOut() {
    // What do I do...?
    // How do I check if they are all filled out...?
}

// Generate sudoku puzzle
function generatePuzzle(num) {
    for(var i = 0; i < solution1.length; i++) {
        for(var j = 0; j < solution1[i].length; j++) {
            rowVal[i][j] = solution1[i][j];
        }
    }
    for(var h = 1; h <= 10; h++) {
        fiddle(rowVal);
    }
    for(var m = 0; m < 81; m++) {
        document.forms[1].elements[m].style.color = 'black';
    }
    putCellVal();
    emptyCells(num);
    for(var f = 0; f < 81; f++) {
        if (document.forms[1].elements[f].value != '') {
            document.forms[1].elements[f].readOnly = 'readonly';
        }
    }
    document.getElementById('CA').style.display = 'inline-block';
    document.getElementById('SS').style.display = "inline-block";
    document.getElementById('CP').style.display = "inline-block";
}

Any help would be appreciated!

JSFiddle Link: http://jsfiddle.net/oliverni/95w8z/

Foi útil?

Solução

Here is the function I wrote that iterates through all the input's with type text and increments a variable with each blank field. Then, if there are no blank fields, it shows the button.

function checkFilledOut() {
    numBlank = 0;
    $('input[type="text"]').each(function() {
       var val = $(this).val();
       if(val == "" || val == 0) {
           numBlank+=1;
       }
    });
    if(numBlank == 0) {
        $('#CA').show();
    }
    else {
        $('#CA').hide();
    }
}

Working fiddle here.

Outras dicas

The easiest way to do that would be to simply check if all your array cells are filled with a for loop after a value is changed.

A bit more complex, but perhaps less on memory would be to just keep a counter of how many are full, by checking if the box had a value, and has a value (Explained below) and then when you reach 81, you run the function to check the solution.

Explanation: Basically, check the last value, so you know if you already had something there, and then if there wasn't, and now is, ++, if it was and still is, nothing, and if there was, and now is not, --. To get the old value, reference here: How to get old Value with onchange() event in text box

You'll want to use the second answer, with 46 upvotes.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top