mardi 6 décembre 2016

javascript concat() method adds newline randomly

I'm writing a JS code that reads the checkboxes in a particular , checks if they're selected, and if yes, appends their value to a string. This is the code that I have:

    var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
    var str="";
    for(var i =0; i< checkboxArr.length;i++){
        var cb = checkboxArr[i];
        if(cb.checked){
            var newVal=cb.value;
            str=str.concat(newVal);
            str=str.concat(",");
        }
    }
    alert(str);

The string that I get is:

value1
,value2
,value3

How are these newlines coming in the string ?

Also, the occurance of these newlines is random - sometimes they appear, sometimes I get the desired string.

I also tried combining the concat() calls into 1 statement, and I used the += operator as well, but no luck.

Any guidance is earnestly appreciated. Thanks




Aucun commentaire:

Enregistrer un commentaire