尝试检测是否有任何检查值包含特定字符串

时间:2019-02-24 16:08:14

标签: javascript html

我正在尝试从一系列复选框中获取所有选中的输入选项的值,并查找是否有选中的值与特定字符串匹配:

function admissible() {
  var b = 4;
  var answer = '';
  var elementsList = document.querySelectorAll("#question5" + " input:checked");

  //get the selected checkbox values for the missing elements
  if (elementsList.length >= 0) { //Code works only if some checkbox is checked
    if ((elementsList.indexOf("photo") > -1) || (elementsList.indexOf("name") > -1)) { //yes
      answer = 'yes';
    } else {
      answer = 'no';
    }
  } else {
    //display error: you must select a value
  }
  console.log(answer);
}
<div class="questionholder" id="question5">
  <div>
    <h5>Select all elements</h5>
    <input class="input5" type="checkbox" id="elementName" name="element" value="name"><label for="elementName"><p class="radioChoice">Name</p></label>
    <input class="input5" type="checkbox" id="elementPhoto" name="element" value="photo"><label for="elementPhoto"><p class="radioChoice">Photo</p></label>
    <input class="input5" type="checkbox" id="elementSignature" name="element" value="signature"><label for="elementSignature"><p class="radioChoice">Signature</p></label>
  </div>
  <div class="holdButtons">
    <a class="text2button" onclick="admissible()">Next</a>
  </div>
</div>

elementsList似乎没有存储复选框的值。我该如何解决?

JSFiddle

4 个答案:

答案 0 :(得分:4)

此代码中存在多个错误。我也做了一些修改,使其更简单。

  1. 您必须使用.indexOf()而不是.indexOF()。诸如此类的小错字可能会使您的整个代码丢掉。
  2. 对于document.querySelectorAll,您只需要input:checked#question5完全没有必要(因为所有值的ID都不为question5)。
  3. .querySelectorAll返回一个NodeList,它更像一个对象而不是一个数组。因此,.indexOf()对此无效。您必须像下面的代码片段一样使用for循环或.forEach()
  4. 我将answer的默认值设置为"no",如果找到照片或名字,它将默认值设置为"yes"(这比拥有{{ 1}}的声明。)

以下代码段适用于您。

if else
function admissible() {
  var b = 4;
  var answer = 'no';
  var elementsList = document.querySelectorAll("input:checked");

  //get the selected checkbox values for the missing elements
  if (elementsList.length >= 0) { //Code works only if some checkbox is checked

    elementsList.forEach(e => {
      if (e.value == "photo" || e.value == "name") {
        answer = "yes";
      }
    });

  } else {
    //display error: you must select a value
  }
  console.log(answer);
}

答案 1 :(得分:3)

您发布的代码中有很多错误。以下示例中的代码修复了它们。这些评论说明了解决方法。

小摘要:

查询选择器

"#question5" + " input:checked"

上面的queryselector看起来错误。它将起作用,但是您可以将其组合为一个字符串。

"#question5 > div:first-child > input:checked"

此查询选择器将进行更安全的选择。它会通过document.querySelectorAll选择类型为id question5的元素的第一个div子元素中检查的所有type输入元素。

遍历节点列表

由于document.querySelectorAll返回的nodelist(类似数组)实际上不是数组。在您的代码中,您使用了length检查到<= 0。这将始终执行if。放下=。现在,只有在nodelist至少有一个条目时才会触发if。

然后,我们使用Array.fromnodeList转换为数组,并使用Array.prototype.some对其进行循环。会迭代每个元素,如果一个条件匹配,它将返回true。

我们使用String.prototype.search而不是String.prototype.indexOf,因为我们可以使用正则表达式一次性查找值name|photo|(管道)告诉代码查找namephoto。如果结果不是-1,那么我们找到了值。

工作示例

function admissible(method) {
  var b = 4;
  var answer = '';
  var elementsList = document.querySelectorAll("#question5 > div:first-child > input:checked"); //fixed the query selector

  //get the selected checkbox values for the missing elements
  if (elementsList.length > 0) { //Code works only if some checkbox is checked
    //cast the node list to array and use array.some to iterate over entries. If one value is found answerFilter will be true.  

    if (method == "some") {
      var answerFilter = Array.from(elementsList).some(function(element) {
        return element.value.search(/name|photo/i) != -1; //check with regexp if value contains photo or name
      });
    }
    else
    {
    
      //map returns an array and lets us return a value we want.
      var answerFilter = Array.from(elementsList).map(function(element) {
        return element.value;
      });
      //now use indexOf like in the original code
      if (answerFilter.indexOf("name") > -1 || answerFilter.indexOf("photo") > -1)
      {
        answerFilter = true;
      }
      else
      {
        answerFilter = false;
      }
    }
    answerFilter ? answer = "yes" : answer = "no"; //use shorthand if/else

  } else {
    //display error: you must select a value
  }
  console.log(answer);
}
* {
  font-family: tahoma;
  font-size: 10pt;
}

div.questionholder>div:first-child {
  display: grid;
  grid-template-columns: 20px auto;
  width: 100%;
}

h5 {
  grid-area: 1 2;
  white-space: nowrap;
}

label {
  grid-column: 2;
}

label>p {
  display: inline;
}

input {
  grid-column: 1;
}

div.holdButtons {
  margin: 10px 5px;
}

div.holdButtons>a {
  padding: 5px;
  background-color: #f4f4f4;
  cursor: pointer;
  border-radius: 4px;
}

div.holdButtons>a:hover {
  background-color: #e1e1e1;
}
<div class="questionholder" id="question5">
  <div>
    <h5>Select all elements</h5>
    <input class="input5" type="checkbox" id="elementName" name="element" value="name"><label for="elementName"><p class="radioChoice">Name</p></label>
    <input class="input5" type="checkbox" id="elementPhoto" name="element" value="photo"><label for="elementPhoto"><p class="radioChoice">Photo</p></label>
    <input class="input5" type="checkbox" id="elementSignature" name="element" value="signature"><label for="elementSignature"><p class="radioChoice">Signature</p></label>
  </div>
  <div class="holdButtons">
    <a class="text2button" onclick="admissible('some')">Next <i>(Array.some)</i></a>
    <a class="text2button" onclick="admissible('map')">Next <i>(Array.map)</i></a>
  </div>
</div>

答案 2 :(得分:0)

order_id

您已经获得了需要遍历的复选框的完整列表,以查找是否已选中要查找的任何复选框。

select o.id, o.number, p.prices
from orders o left join products p
on p.order_id = o.id
union all
select null, null, p.prices
from products p
where p.order_id is null

答案 3 :(得分:0)

我认为这段代码是检查输入是否已被检查并检索其值的更慷慨的方法。是更多的伪代码,但您可以从这里继续:

var inputList = document.querySelectorAll(".input5");

for (var i = 0; i < inputList.length; i++) {
    if (inputList[i].checked) {
        if (/^(photo|name)$/.test(inputList[i].value)) {
            // your code here
        }
    }
}
相关问题