从选中的复选框中获取所有值并放入textarea

时间:2013-12-16 02:31:12

标签: javascript html

我希望通过javascript将所有复选框值放入文本区域,一旦取消选中,它将从数组中弹出...这是代码:

<form enctype="multipart/form-data" method="get" id="frmMain" name="frmMain">
    <input type = "checkbox" id = "chk1" value = "CheckBox1" onclick ='checkTickArea(this.id)'> 
    <input type = "checkbox" id = "chk2" value = "CheckBox2" onclick = 'checkTickArea(this.id)'> 
    <input type = "checkbox" id = "chk3" value = "CheckBox3" onclick = 'checkTickArea(this.id)'> 
    <input type = "checkbox" id = "chk4" value = "CheckBox4" onclick = 'checkTickArea(this.id)'> 
    <input type = "checkbox" id = "chk5" value = "CheckBox5" onclick = 'checkTickArea(this.id)'>
    <textarea id= "taSignOff" style="width:180px;height:90px;font-size:20px; resize: none;" rows="3" readonly> </textarea>
</form>

javascript:

var selectedvalue=[];
function checkTickArea(id)
   {

       $('#'+id).change(function () {
           //If checked then push the value
           if( $('#'+id).is(":checked"))
           {
               selectedvalue.push($('#'+id).attr("value"));
           }else
           {
               //This is what pops the value from the array when the checkbox is unchecked.
             /*  var index = selectedvalue.indexOf($('#'+id).attr("value"));
               if (index > -1) {
                   selectedvalue.splice(index, 1);
               }*/
               selectedvalue.splice(selectedvalue.indexOf($(this).attr("value")),1);
           }
           document.getElementById('taSignOff').value = selectedvalue.join("->\n");
       });
   }

此外,此功能仅适用于Firefox ...但在Chrome和IE浏览器中,它不起作用......

2 个答案:

答案 0 :(得分:0)

这对我有用,虽然我不知道你为什么不在文本区域使用jQuery: jsFiddle

HTML:

<form enctype="multipart/form-data" method="get" id="frmMain" name="frmMain">
    <input type = "checkbox" id = "chk1" value = "CheckBox1" /> 
    <input type = "checkbox" id = "chk2" value = "CheckBox2" /> 
    <input type = "checkbox" id = "chk3" value = "CheckBox3" /> 
    <input type = "checkbox" id = "chk4" value = "CheckBox4" /> 
    <input type = "checkbox" id = "chk5" value = "CheckBox5" />
    <textarea id= "taSignOff" style="width:180px;height:90px;font-size:20px; resize: none;" rows="3" readonly> </textarea>
</form>

JavaScript的:

var selectedvalue = [];

$('input[type="checkbox"]').on('change', checkTickArea);

function checkTickArea() {

    //If checked then push the value
    if ($(this).is(":checked")) {
        selectedvalue.push($(this).val());
    } else {
        selectedvalue.splice(selectedvalue.indexOf($(this).val()), 1);
    }

    // Why not use jQuery tho?
    //$('taSignOff').val(selectedvalue.join("->\n"));
    document.getElementById('taSignOff').value = selectedvalue.join("->\n");
}

答案 1 :(得分:0)

删除内联javascript并执行:

var elems = $('[id^="chk"]');

elems.on('change', function() {
    $('#taSignOff').val(
        elems.filter(':checked').map(function() {
            return this.value;
        }).get().join("->\n")
    );
});

FIDDLE