简体   繁体   English

如何从从 Javascript 创建的复选框中检索值?

[英]How do I retrieve the value from a checkbox that was created from a Javascript?

I was following the sample code provided by another post (source: How to display multiple list of checkboxes dynamically on dropdown list ), as it has the function that was exactly what I was trying to do for my webpage.我正在关注另一篇文章提供的示例代码(来源: 如何在下拉列表中动态显示多个复选框列表),因为它具有 function 这正是我试图为我的网页做的。 However, I am having trouble retrieving the value of the checkbox that the user has selected, as the checkbox was dynamically created from the javascript.但是,我无法检索用户选择的复选框的值,因为该复选框是从 javascript 动态创建的。 I tried debugging by inserting an alert function, and I was return with a "[Object NodeList]".我尝试通过插入警报 function 进行调试,然后返回“[Object NodeList]”。

How can I retrieve the individual value(s) base on the checkbox that the user has selected?如何根据用户选择的复选框检索单个值? For example, if user has selected "apple", I want to retrieve the value "apple".例如,如果用户选择了“apple”,我想检索值“apple”。 But if the user has selected "apple" and "Orange", I want to retrieve the value "apple" and "orange".但是如果用户选择了“apple”和“orange”,我想检索值“apple”和“orange”。

UPDATE更新

Thank you everyone for your comments and sample codes.谢谢大家的意见和示例代码。 I have edited the code below to retrieve the user-selected checkbox.我编辑了下面的代码以检索用户选择的复选框。

HTML: HTML:

<form id="product_form">
  <div class="row" id="row1">
      <div class="col-8">
          <label><strong>FoodCategory:</strong></label>
          <select id="model" name="model" onchange="populate(this.id, 'food')">
              <option value="select">--Select Category--</option>
              <option value="Fruit">Fruit</option>
              <option value="vegetable">Vegetable</option>
          </select>
      </div>
      <div class="col-8">
          <label><strong>Outcome:</strong></label>
          <div id="food"></div>
      </div>
  </div>
</form>
<button onclick="getResult()">Get Result</button>

Javascript: Javascript:

var mappingData = {
    "fruit": {
      "destination": ["Apple", "Orage"]
    },
    "vegetable": {
      "destination": ["Cabbage", "Carrot"]
    }
  };
  
  function populate(model, food) {
    var mod = document.getElementById('model');
    var scenario = document.getElementById('food');
    scenario.innerHTML = "";
    mappingData[mod.value].destination.forEach(function(item) {
      createCheckBox(item, scenario)
    });
  }
  
  function createCheckBox(value, parent) {
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.name = "food";
    checkbox.value = value;
  
    var label = document.createElement('label')
    label.htmlFor = value;
    label.appendChild(document.createTextNode(value));
  
    parent.appendChild(checkbox)
    parent.appendChild(label)
    parent.appendChild(document.createElement("br"))
  }

function getResult() {
    let checkboxes = document.querySelectorAll('input[name="food"]:checked');
    let values = [];
    checkboxes.forEach((checkbox) => {
        values.push(checkbox.value)
    });
    alert(values);
}

Write this code when all javascript code done...完成所有 javascript 代码后编写此代码...

<script> 
if (document.getElementById('youid').checked) {
        alert(document.getElementById('youid').value);
    }</script>

Assuming you have an attribute to select those checkboxes, this code would work:假设您具有 select 这些复选框的属性,则此代码将起作用:

 function do_submit(form) { var result = []; var checkboxes = form.querySelectorAll(".my-checkbox").forEach(function(elem) { if (elem.checked) { result.push(elem.value); } }); form.querySelector("[name=chekboxes]").value = result.join(","); // to cancel: return false // to submit: // form.submit(); }
 <form onsubmit="return do_submit(this); "> <label><input type="checkbox" class="my-checkbox" value="apple"> apple </label><br> <label><input type="checkbox" class="my-checkbox" value="banana"> banana </label><br> <label><input type="checkbox" class="my-checkbox" value="cabbage"> cabbage </label><br> <:-- should be hidden: --> <input type="text" name="chekboxes" value=""> <input type="submit"> </form>

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

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