简体   繁体   English

如何选中/取消选中复选框并在 textarea 中显示?

[英]How to check/uncheck the checkbox and show in textarea?

The checked value appears in text area.选中的值出现在文本区域中。

If I check more than two, I want to add the value to the newline.如果我检查两个以上,我想将值添加到换行符。 If I uncheck, I want to make the value disappear.如果我取消选中,我想让该值消失。 If I check all, I want to add all values如果我检查所有,我想添加所有值

I hope it works like the uploaded picture.我希望它像上传的图片一样工作。 Thanks for your help.谢谢你的帮助。

    <textarea rows="8" name="mobile" class="form-control" id="mobile" placeholder=""></textarea>
            <div class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input" id="customCheck1">
                <label class="custom-control-label" for="customCheck1" value="">all</label>
            </div>
            <div class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input" value="1" id="customCheck2">
                <label class="custom-control-label" for="customCheck2">1</label>
            </div>
            <div class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input" value="2" id="customCheck3">
                <label class="custom-control-label" for="customCheck3">2</label>
            </div>
            <div class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input"  value="3" id="customCheck4">
                <label class="custom-control-label" for="customCheck4">3</label>
            </div>
                <script>
                    var radio = document.querySelectorAll(".custom-control-input");
                    var mobile = document.getElementById("mobile");
                    function checkBox(e){
                    mobile.value = e.target.value;
                    }
                    radio.forEach(check => {
                    check.addEventListener("click", checkBox);
                    });
                </script>

在此处输入图像描述

While it may sound like a bit of overkill, I would handle this with an Array or Object instead of trying to manage it in your textarea.虽然这听起来有点矫枉过正,但我会使用 Array 或 Object 来处理它,而不是尝试在你的 textarea 中管理它。 I'd then make sure the textarea contains only the data in whatever you choose..然后,我会确保 textarea 仅包含您选择的任何数据。

For example:例如:

const selectedDataMap = {};
const radio = document.querySelectorAll(".custom-control-input");
const mobile = document.getElementById("mobile");

const checkBox = (e) => {
    if (!selectedDataMap[e.target.id]) {
        selectedDataMap[e.target.id] = true;
    }

    selectedDataMap[e.target.id] = e.target.checked;

    mobile.value = Object.keys(selectedDataMap).filter(id => { 
        const checkboxVal = document.querySelector(id).value || 'all';
        return selectedDataMap[id] === true ? checkboxVal : '';
    }).join("\n");
};

radio.forEach(check => check.addEventListener("click", checkBox));

DISCLAIMER: The above is untested.免责声明:以上内容未经测试。 There are literally thousands of ways of improving upon this too.实际上也有成千上万种改进方法。 After all - it's only supposed to be an example.毕竟——这只是一个例子。

The point though by doing this is because you can track/control what's in an array or object map a lot easier than trying to sort line-by-line through text and all that...这样做的重点是因为您可以跟踪/控制数组或 object map 中的内容,这比尝试通过文本逐行排序容易得多......

You could also expand your original solution too by creating a data object (something like: [{ id: 'customCheck1", value: "", label: "all", checked: false}...] ) and then print out all your checkboxes based on this object. You could then easily track your checked/unchecked by flipping the flag and then just printing out all the values in the text box. Like I said earlier though - literally thousands of ways to do this =]您也可以通过创建数据 object 来扩展您的原始解决方案(类似于: [{ id: 'customCheck1", value: "", label: "all", checked: false}...] )然后打印出所有您的复选框基于此 object。然后,您可以通过翻转标志轻松跟踪您的选中/未选中状态,然后打印出文本框中的所有值。就像我之前所说的那样——实际上有数千种方法可以做到这一点 =]

Use whatever you think works best though!使用任何你认为最有效的方法! Good luck!祝你好运!

<script>
  var radio = document.querySelectorAll('.custom-control-input');
  var mobile = document.getElementById('mobile');

  function checkBox(e) {
    var str = mobile.value;

    if (e === undefined) return;

    if (e.target.value === 'on') return selectAll();

    if (str.includes(e.target.value))
      return (mobile.value = str
        .split('\n')
        .filter((n) => n.indexOf(e.target.value) == -1)
        .join('\n'));

    mobile.value = str + e.target.value + '\n';
  }

  function selectAll() {
    for (var i = 1; i < radio.length; i++) {
      radio[i].click();
    }
    checkBox();
  }

  radio.forEach((check) => {
    check.addEventListener('click', checkBox);
  });
</script>

Refs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox参考: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

  • Wrap <form> around everything.<form>包裹在所有内容中。
  • Assign a class to the All checkbox and then a different one to the rest of the checkboxes to share.将 class 分配给 All 复选框,然后将另一个分配给要共享的复选框的 rest。 In the example below it's: .all and .chx .在下面的示例中,它是: .all.chx
  • Add the event handler to the <form> so that any "change" events happen on or within <form> are captured.将事件处理程序添加到<form>以便捕获发生在<form>上或内部的任何“更改”事件。
  • Design the event handler to react to only specific tags and ignore the rest.设计事件处理程序以仅对特定标签做出反应并忽略 rest。 See event delegation .请参阅事件委托

The example stores an array of values and uses various Array methods to add, remove, and calculate the numbers within it.该示例存储了一个值数组,并使用各种 Array 方法来添加、删除和计算其中的数字。 The details are commented in the example.详细信息在示例中进行了注释。

 // This is <form> const form = document.forms[0]; // Initialize all and sum let all = []; let sum = 0; // Define helper function const getSum = (x, y) => x + y; // Pass the event object const chxSum = event => { /* This is all form controls of <form> ie <textarea>, and all <input> */ const IO = event.currentTarget.elements; // This is the tag the user clicked const clicked = event.target; // This is the value of clicked as a real number let valNum = Number(clicked.value); // This is a NodeList of all.chx as an array const allChx = [...document.querySelectorAll('.chx')]; /* if the tag that the user clicked has class.chx... */ if (clicked.matches('.chx')) { /*...see if it's checked -- if it is then add it's value into the all array... */ if (clicked.checked) { all.push(valNum); //...otherwise remove the value from all array } else { all.splice(all.indexOf(valNum), 1); } /* But if the clicked tag has class.all... */ } else if (clicked.matches('.all')) { /*...see if it's clicked and if it is then check all of the.chx and reset the all array to [1,2,3]... */ if (clicked.checked) { allChx.forEach(chx => chx.checked = true); all.length = 0; all = [1, 2, 3]; /*...otherwise uncheck all.chx and empty the all array */ } else { allChx.forEach(chx => chx.checked = false); all.length = 0; } // end this function if clicked was anything else } else { return false; } // Get the sum of all values in all array sum = all.reduce(getSum, 0); // Display sum in <textarea> IO.mobile.value = sum; }; /* Add event handler on <form>. if any changes are detected on or within the <form> it will be captured */ form.onchange = chxSum;
 <,DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1: shrink-to-fit=no"> <link href="https.//cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min:css" rel="stylesheet"> <style></style> </head> <body> <main class="container"> <section class="row"> <form class='col'> <textarea rows="8" name="mobile" class="form-control" id="mobile" placeholder=""></textarea> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input all" id="customCheck1"> <label class="custom-control-label" for="customCheck1">all</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input chx" value="1" id="customCheck2"> <label class="custom-control-label" for="customCheck2">1</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input chx" value="2" id="customCheck3"> <label class="custom-control-label" for="customCheck3">2</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input chx" value="3" id="customCheck4"> <label class="custom-control-label" for="customCheck4">3</label> </div> </form> </section> </main> <script src="https.//cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM