简体   繁体   中英

how to write increment document get element by id

  <div class="form-group col-md-12 input_fields_wrap">
          <label for="merk">Merk</label>
          <div class="input-group">
            <input type="text" class="form-control" name="merk[]">
            <span class="input-group-btn">
              <button class="btn btn-secondary add_field_button" type="button">add row</button>
            </span>
          </div>
          <div id="1"></div>
        </div>

**above my html code and when i click add row will append new row with id="2" ** and this is my javascript code

function validasiForm(){
    var y = document.getElementsByName('merk[]').length;
    console.log(y);
    for (var i = 0; i < y ; i++) {
        var merk = document.getElementsByName('merk[]')[i].value;
        if (merk == null || merk == "") {
        document.getElementById("i").innerHTML="<p class='color-red'>*validation message</p>";
        // document.getElementById("merk2").innerHTML="<p class='color-red'>*nama merk harus di isi</p>";
          return false;
      }
    }
  }

so my question is how to dynamically show validation message with dynamic get element by id?

document.getElementById("i") is literally looking for an element with the ID "i". Use a different naming convention, like "elem1" or something. Then document.getElementById("elem"+i) .

It's worth mentioning that IDs should not begin with numbers anyway. This will cause an error as a variable name in javascript (IDs are implicitly global variables) and CSS will ignore it. It might never cause you pain, but hey-- good to know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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