0

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

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

<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>
4

1 回答 1

1

这是一种无框架(无 jQuery/原型)的方法。

示例: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')], "")); 
    }
});
于 2012-04-30T18:01:54.487 回答