addEventListener到多个复选框 [英] addEventListener to multiple checkboxes

查看:78
本文介绍了addEventListener到多个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我有一个简单的表单,其中包含4个复选框作为席位.我想做的是,当访客选择ID为A2A4的座位复选框时,我希望在单击名称为<的段落后立即显示这些ID及其总值. c2>.单击按钮[立即保留]后,应将总值分配给名为$TotalCost的变量.

Below, I have a simple form that has 4 checkboxes acting as seats. What I am trying to do is when a visitor chooses, say, seat checkboxes with IDs A2 and A4, I want those IDs and their total value to be shown instantly after clicking inside a paragraph with which have a name called id="demo". When a button [Reserve Now] has been clicked, the total value should be assigned to a variable called $TotalCost.

我该怎么做?这是我的代码:

How can I accomplish this? Here's my code:

<!DOCTYPE html>
<html>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>

<p id="demo">
Selected Seat(s)
<br>
<br>
Total: USD  <input type="submit" value="Reserve Now">
</form>

</p>

<script>
document.getElementById("A1").addEventListener("click", displayCheck);

function displayCheck() {
    document.getElementById("demo").innerHTML = ;
}

    </script>
    </body>
    </html>

推荐答案

这是在复选框上设置事件侦听器的一种方法.我使用document.querySelectorAll("input[type='checkbox']");从DOM中获取所有复选框元素,并使用循环将侦听器添加到每个复选框. selections对象可以跟踪已检查的项目.单击复选框后,项值将通过键添加到对象.取消选中该复选框时,该项目将从对象中删除.每当发生操作时,都会根据selections的内容使用所有相关信息来更新DOM.

Here's one approach to setting up event listeners on checkboxes. I used document.querySelectorAll("input[type='checkbox']"); to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections object can keep track of which items have been checked. When a checkbox is clicked on, the item values are added to the object by key. When the checkbox is off, the item is deleted from the object. Whenever an action happens, the DOM is updated with all relevant information based on the contents of selections.

这个例子只是一个简单的草图,可以为您提供想法.您将需要另一个事件侦听器作为提交"按钮,以处理将表单数据发送到PHP脚本的过程.我将其保留为练习.

This example is just a quick sketch to give you the idea. You'll need another event listener for your submit button to handle sending the form data to your PHP script. I'll leave that as an exercise.

请注意,您提供的HTML无效,因为嵌套已损坏. HTML验证器有助于解决此类问题.

Note that the HTML you've provided is invalid because nesting is broken. A HTML validator can be helpful for fixing these sort of problems.

var selections = {};
var checkboxElems = document.querySelectorAll("input[type='checkbox']");
var totalElem = document.getElementById("seats-total");
var seatsElem = document.getElementById("selected-seats");

for (var i = 0; i < checkboxElems.length; i++) {
  checkboxElems[i].addEventListener("click", displayCheck);
}

function displayCheck(e) {
  if (e.target.checked) {
    selections[e.target.id] = {
      name: e.target.name,
      value: e.target.value
    };
  } 
  else {
    delete selections[e.target.id];
  }

  var result = [];
  var total = 0;

  for (var key in selections) {
    var listItem = "<li>" + selections[key].name + " " +
                   selections[key].value + "</li>";
    result.push(listItem);
    total += parseInt(selections[key].value.substring(1));
  }

  totalElem.innerText = total;
  seatsElem.innerHTML = result.join("");
}

<!DOCTYPE html>
<html lang="en">
<head>
  <title>...</title>
</head>
<body>
  <h2>Please choose a seat to book</h2>
  <form action="/action_page.php" method="post">
    <input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
    <input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
    <input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
    <input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
    <p>Selected Seat(s)</p>

    <!-- container for displaying selected seats -->
    <ul id="selected-seats"></ul>
    
    <div>
      Total: $<span id="seats-total">0</span> USD 
      <input type="submit" value="Reserve Now">
    </div>  
  </form>
</body>
</html>

通常,您将需要动态生成元素并添加事件侦听器.这是一个玩具示例:

Often, you'll want to generate the elements dynamically and add event listeners. Here's a toy example:

for (let i = 0; i < 1000; i++) {
  const checkbox = document.createElement("input");
  document.body.appendChild(checkbox);
  checkbox.type = "checkbox";
  checkbox.style.margin = 0;
  
  checkbox.addEventListener("mouseover", e => {
    e.target.checked = !e.target.checked;
  });
  
  checkbox.addEventListener("mouseout", e =>
    setTimeout(() => {
      e.target.checked = !e.target.checked;
    }, 1000)
  );
}

这篇关于addEventListener到多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆