复选框值基于选择添加或删除到文本区域

时间:2012-04-30 17:17:06

标签: javascript html

如何根据用户选择上面的复选框,将复选框“变量值”添加到我的文本区域。我需要它来添加或删除,下拉工作正常只需要帮助,复选框似乎无法让它们工作。

这是我到目前为止的代码:

<html>
<head>

</head>

<body>


  Image 1 <input type="checkbox" name="ImageVar1" id="ImageVar1" /><br />
  Image 2 <input type="checkbox" name="ImageVar2" id="ImageVar2" /><br />
  Image 3 <input type="checkbox" name="ImageVar3" id="ImageVar3" /><br />
  Image 4 <input type="checkbox" name="ImageVar4" id="ImageVar4" />

<p>&nbsp;</p>

  <select id="dropdown">
    <option value="">None</option>
    <option value="textVar1">text 1</option>
    <option value="textVar2">text 2</option>
    <option value="textVar3">text 3</option>
    <option value="textVar4">text 4</option>
  </select>

<p>&nbsp;</p>

  <textarea id="mytext"></textarea>

<script type="text/javascript">

var textVar1 = 'this is going to be a long sting of text for text 1 value ';
var textVar2 = 'this is going to be a long sting of text for text 2 value ';
var textVar3 = 'this is going to be a long sting of text for text 3 value ';
var textVar4 = 'this is going to be a long sting of text for text 4 value ';

var ImageVar1 = 'Image 1 value ';
var ImageVar2 = 'Image 2 value ';
var ImageVar3 = 'Image 3 value ';
var ImageVar4 = 'Image 4 value ';

var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown');

mydropdown.onchange = function(){
mytextbox.value = mytextbox.value  + window[this.value];

}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是一种无框架(无jQuery / prototype)方式。

示例:http://jsfiddle.net/S5vcW/6/

虽然有些浏览器支持document.querySelectorAll("input[type='checkbox']"),但这会使脚本更简单,更高效。

var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type === "checkbox" && inputs[i].name.indexOf('ImageVar') > -1) {
        inputs[i].onchange = function(){
            if(this.checked){
                mytextbox.value = mytextbox.value  + ImageVars[this.name];
            }else{
                mytextbox.value = mytextbox.value.replace(ImageVars[this.name], ""); 
            }
        }
    }  
}

这是一个完成同样事情的jQuery版本。

示例:http://jsfiddle.net/S5vcW/5/

$("input[type='checkbox'][name*='ImageVar']").change(function(){
    var $chk = $(this); 
    if($chk.prop('checked')){
        $mytextbox.val($mytextbox.val() + ImageVars[$chk.attr('name')]);
    }else{
        $mytextbox.val($mytextbox.val().replace(ImageVars[$chk.attr('name')], "")); 
    }
});