如何遍历具有随机元素的表单

问题描述 投票:4回答:2

我试图遍历在随机元素中有标签的表单,并检查标签是否与给定的标签名称匹配,如果匹配,我正在为该元素添加一个类。但是我无法让它工作,我该怎么做?

这是我尝试过的。

在div之类的随机元素中包含标签的表单

<form id="grtform">
    <div id="section-1">
        <lable>Currency type</lable>
        <input type="text" name="currencyType">
    </div>

    <div id="section-2">
        <lable>Currency rate</lable>
        <input type="text" name="currencyRate">
    </div>

        <lable>Currency of country</lable>
        <input type="text" name="currencyCountry">

    <div id="section-3">
        <div class="formData">
            <lable>Currency due</lable>
            <input type="text" name="currencyDue">
        </div>
    </div>
  </form>

Jquery代码:

$("#grtform").each(function(){
                var matchLable = "Currency due"
                var lable = $(this).find('label').text();
                if(matchLable == lable){
                    $(this).addClass('matchFound');
                }
      });
javascript jquery
2个回答
5
投票

你需要循环标签,而不是形式

$("#grtform lable").each(function(){ // selecting all labels of form
                var matchLable = "Currency type"
                var lable = $(this).text(); // changed here too
                if(matchLable == lable){
                    $(this).addClass('matchFound');
                }
      });

在上面的代码中,这指的是当前迭代标签。

修剪了一下

$("#grtform lable").each(function(){ // selecting all labels of form
                if($(this).text() == "Currency type"){
                    $(this).addClass('matchFound');
                }
      });

0
投票

您还可以使用以下方式: -

var allLables = document.querySelectorAll("#grtform lable");
for(var i = 0; i < allLables.length; i++){
  var matchLable = "Currency type";
  var lable = allLables[i].innerText; // changed here too
  if(matchLable == lable){
    allLables[i].classList.add("matchFound");
  }
}
<form id="grtform">
    <div id="section-1">
        <lable>Currency type</lable>
        <input type="text" name="currencyType">
    </div>

    <div id="section-2">
        <lable>Currency rate</lable>
        <input type="text" name="currencyRate">
    </div>

        <lable>Currency of country</lable>
        <input type="text" name="currencyCountry">

    <div id="section-3">
        <div class="formData">
            <lable>Currency due</lable>
            <input type="text" name="currencyDue">
        </div>
    </div>
  </form>
© www.soinside.com 2019 - 2024. All rights reserved.