如何使用复选框创建字符串?

时间:2018-02-21 16:14:29

标签: javascript arrays checkbox

我试图得到一个结果,字符串将转为"该人选择了A,B,C。"

但是使用下面的代码,如果我检查了所有三个框,我只能生成: 这个人选了A, 该人选择了A,B, 该人选择了A,B,C,

我不希望生成的笔记有3条不同的行。

        var notes = "";
        var reason = "";
        for (j=0; j<document.reason.reasonqst.length; j++){
            if (document.reason.reasonqst[j].checked==true){
                notes += "The person selected";
                if (j==0)
                    reason += "A, ";
                if (j==1)
                    reason += "B, ";
                if (j==2)
                    reason += "C,";
                notes += "" + reason + "\r";

            }
        }



    <form id="reason" name="reason" method="post" action="">
    <table>
        <tr>        
            <td>BPC: <input onclick="ds_sh(this);" name="reason" id="reason" readonly="readonly" style="cursor: text" /><br /></td>
        </tr>
        <tr>
            <td style="width: 120px;"><input type="checkbox" name="reasonqst" id="reasonqst" />A</td>
            <td style="width: 120px;"><input type="checkbox" name="reasonqst" id="reasonqst" />B</td>
            <td style="width: 120px;"><input type="checkbox" name="reasonqst" id="reasonqst" />C</td>

        </TR>
    </table>
         </form>

2 个答案:

答案 0 :(得分:2)

将音符变量移到外部循环并附加单个值

notes = "The person selected";
for (j=0; j<document.reason.reasonqst.length; j++){
            if (document.reason.reasonqst[j].checked==true){
                if (j==0)
                    reason += " 1";
                if (j==1)
                    reason += ", 2 ";
                if (j==2)
                    reason += ", 3";

            }
        }
notes += "" + reason + "\r";

答案 1 :(得分:0)

我建议你使用较轻的版本,你可以从你的变量和最终值几乎相同的事实中获利,它只有1个数值差异:

    var reason = "";
    let personsSelected = [];
    for (j=0; j<document.reason.reasonqst.length; j++){
        if (document.reason.reasonqst[j].checked==true){
            personsSelected.push(j+1);
        }
    }
    let notes = `The person selected ${personsSelected.join(',')}` + "\r";