John
John

Reputation: 47

How to change the parameters of getElementById in a loop

I am working on a form, and I would like to reset the lines individually without using reset. How to vary the values ​​of the attribute passed as parameter of the method getElementById in JavaScript using a loop? Here is an example of my source code below:

<script>
         var element = document.getElementById('#re');
    element.addEventListener('click', function() {
        document.getElementById("#id1").value = "";
        document.getElementById("#id2").value = "";
        document.getElementById("#id3").value = "";
    });
</script>

Upvotes: 1

Views: 1326

Answers (3)

David Hedlund
David Hedlund

Reputation: 129802

For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):

for(var i = 1; i <= 3; i++) {
   document.getElementById('id' + i).value = '';
}

If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:

var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
   element.value = '';
});

Upvotes: 0

hjrshng
hjrshng

Reputation: 1826

Instead of using ids, you can loop through your inputs for example:

var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].value = "";
}

Upvotes: 1

Lennholm
Lennholm

Reputation: 7480

Assuming your IDs have the format shown in your example:

for (var i = 1; i <= 3; i++) {
  document.getElementById("id" + i).value = "";
}

If that's not the case but you know the ID of every element you can put all IDs in an array and use that:

var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
  document.getElementById(id).value = "";
});

Another solution is to give all the elements you want to reset a specific class and target that:

var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
  element.value = "";
});

Upvotes: 1

Related Questions