Search code examples
javascripthtmldom-eventsinnerhtml

Getting undefined string constraint error in Javascript


I want to pass a Javascript variable as a argument of a function called on onclick event of a checkbox, and the checkbox is created in innerHTML. The code snippet is:

function populateValue(Result) {
    var valueSet = new Array();
    valueSet = Result.split("##");
    for (i = 1; i < valueSet.length - 3; i++) {
        var tr = document.createElement("tr");
        var td = document.createElement("td");
        tr.setAttribute("align", "left");
        tr.className = "table_ce11";
        td.setAttribute("align", "center");
        var code = String(valueSet[i - 1]);
        td.innerHTML = "<input type='checkbox' name='pCheckBox' value='111' id ='" + code + "' onClick=\"javascript:decide('" + code + "')\">";

        tr.appendChild(td);
    }
}

function decide(code) {
    alert("here");
    alert(document.getElementById(code).value);
    if (document.getElementById(code).checked) alert("chked");
    else alert("unchked");
}

while running this, neither am able to set the id nor to pass the argument of the function decide(). I get the error:

"undetermined string constraint".

But if I hardcode the values the function runs fine. Any suggestions on this?


Solution

  • Just for starters

    Split creates an array.

    var valueSet = Result.split("##");

    You need to test if there ARE at least 4 items in the array

    if (valueSet.length <= 3) return 
    for (var i = 1; i < valueSet.length - 3; i++) {
    

    no need to create a string when you string concatenate a string anyway

    var code = valueSet[i - 1];

    No need to use javascript: prefix and no need to pass the code when it is the same as the ID:

    td.innerHTML = '<input type="checkbox" name="pCheckBox" value="111" id ="' + code + '" onClick="decide(this.id)">';

    Also default align is left and you align center on the cell so get rid of

    // tr.setAttribute("align", "left");

    can you post more of the code and tell where things are going wrong exactly?