How to skip a form that has random elements

I am trying to skip a form that has a label inside random elements, and check if the label matches the specified label name, and if so, I add a class to this element. But I can’t make it work, how can I do it?

Here is what I have tried.

A form that has labels inside random elements like a 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 code:

$("#grtform").each(function(){
                var matchLable = "Currency due"
                var lable = $(this).find('label').text();
                if(matchLable == lable){
                    $(this).addClass('matchFound');
                }
      });
+4
source share
2 answers

You need to scroll through the lines, not in the form

$("#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');
                }
      });

In the code above, this refers to the current iteration label.

After trimming the bit

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

You can also use the following method: -

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>
Run code
0
source

Source: https://habr.com/ru/post/1691393/


All Articles