1

I want to be able to change multiple text inputs (but not all) by class, but can't seem to get it working.

Any ideas?

Basically I have multiple reset buttons on the same page I'd like to have 'resetting' the value of the targeted text inputs to nothing.

Here's the code:

$(".reset").on('click', function() {
  document.getElementsByClassName('input-1').value = '';
});

It works fine when using getElementById, but I would rather minimise the code and not have to repeat it each time for every text input.

2 Answers 2

3

You are already using jQuery, so just use

$(".reset").on('click', function() {
  $('.input-1').val('');
});

Notice the . before the class name, same as in .reset.

If you want to use vanilla JavaScript, you have to loop through the HTMLCollection returned by getElementsByClassName:

$(".reset").on('click', function() {
  Array.from(document.getElementsByClassName('input-1')).forEach(el => el.value = '');
});

jQuery does that automatically for you.

Sign up to request clarification or add additional context in comments.

7 Comments

document.getElementsByClassName('input-1').forEach(el => el.value = ''); won't work. Method getElementsByClassName returns NodeList that doesn't have forEach method. NodeList should be converted to an Array using Array.from method or Array.prototype.forEach method should be applied on NodeList via call or apply.
It does have a forEach method, but you are right, it's not really well supported.
You're right. I've mixed up NodesList and HTMLCollection. getElementsByClassName returns HTMLCollection and it doesn't have forEach method.
I don't think you can still do that. But since IE doesn't support fE on HTMLCollections, using array.from makes sense here :-)
I've just checked in Chrome Canary 71 and got the following error: VM259:1 Uncaught TypeError: document.getElementsByClassName(...).forEach is not a function
|
0

You can use an special selector for this job:

let inputs = [... document.querySelectorAll("[class^='input-']")];

inputs.forEach(i  => i.value = "");

class^= will return all the elements containing class attribute starting with "input".

2 Comments

This won't work. You cannot set a value to a NodeList that's returned from querySelectorAll.
This will not work, the return value of querySelectorAll does not have a value attribute as it's an array-like structure with HTML elements in it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.