How to get the length of selected checkboxes

I want to add the + but stop when i reaches the checked length minus 1.


var checkedlength=0; 
for(i=0;i<document.getElementsByName('checkresult').length;++i){
    if (document.getElementsByName('checkresult')[i].checked){
        urlext+=document.getElementsByName('checkresult')[i].value;
        checkedlength++;
        if(i<document.getElementsByName('checkresult').length-1){
            urlext+='+'; 
        }
    }
}

I realize that the document.getElementsByName(‘checkresult’).length in if(i<document.getElementsByName(‘checkresult’).length-1) is not the same as the checked.

You can simplify this a lot by adding the ‘+’ before adding the string. Then you only need to check if the string is the first one you’re adding. Also note the use of i and j, this is an improvement because it means the length doesn’t have to be checked with each iteration.

var checks = document.getElementsByName('checkresult'), urlext = '';
for(var i=0, j = checks.length; i < j; ++i){
    if (checks[i].checked){
        if (urlext.length > 0) urlext += '+';
        urlext+=checks[i].value;
    }
}

I also defined i with the “var” keyword, and urlext at the top. It is bad practice to not declare variables with var, as the global scope becomes polluted if you don’t. It is frowned upon to use lots of global variables unnecessarily and it can cause hard to debug problems.

There’s still something wrong though. The plus is now appearing in front of the string:


var thisurlext='?btitle0='+document.getElementById('vsbtitle_0').value+'&btitle1='+document.getElementById('vsbtitle_1').value+'&username='+document.getElementById('myusername').innerHTML+'&checkresult='; 
var checks = document.getElementsByName('checkresult'); 
for(var i=0, j = checks.length; i < j; ++i){
    if (checks[i].checked){   
        if (thisurlext.length > 0){
            thisurlext += '+';
        } 
        thisurlext+=checks[i].value;
    }
}

I’m getting:
checkresult=+1395+1534

Well, you can figure it out. Look at the bit where you check to see whether to add the “+” at the start of the string or not. It checks the length of thisurlext. You’ve changed the code so that thisurlext already has an initial length. So I suggest making a new string and adding it to that. Then at the end, after the loop, concatenate it to thisurlext.