简体   繁体   中英

Replace text with empty string by class in html using javascript

I'm trying to create a js function which removes text onclick from a certain class of fields in HTML.

When checking Yes in the trigger (onclick), the function is not clearing the data in my target.

This works if I substitute id for class where appropriate, but I need the function to affect 10+ html fields. Can this be accomplished by class?

Note: There is a little extra in the HTML below because there is another js function run onclick in my trigger. I've removed the divs, so it's less cluttered.

JavaScript

function eraseText() {
  document.getElementsByClassName("eraseonupdate").value = "";
}

HTML

Trigger:

<input type="radio" name="exceptionupdate" class="_exceptionupdate" value="Yes" onclick="ExceptionUpdate();eraseText()" />Yes <input type="radio" name="exceptionupdate" class="_exceptionupdate" value="No" onclick="ExceptionUpdate()" />No

Target:

<input type="text" name="Approver" size="20" class="eraseonupdate">

That's because the two methods return different values.

getElementById will return one HTML object (as an id should be unique).
getElementsByClassName will return a HTMLCollection (as classes do not need to be unique). To alter the value of each of the items in this collection, you need to loop over them.

For example

var elements = document.getElementsByClassName("eraseonupdate");

for (var i = 0; i < elements.length; i++) {
    elements[i].value = ""
}

You need to iterate the result of .getElementsByClassName() , to make that easier you can convert it to an array, like so:

 function eraseText() { var elements = document.getElementsByClassName('eraseonupdate'); Array.prototype.slice.call(elements).forEach(function(el) { el.value = ''; }); // if you do not need old browsers to work you could do /* [...elements].forEach(el => { el.value = ''; }); */ } function ExceptionUpdate() { return; } 
 <input type="text" name="Approver" size="20" class="eraseonupdate"> <label><input type="radio" name="exceptionupdate" class="_exceptionupdate" value="Yes" onclick="ExceptionUpdate();eraseText()" />Yes</label> <label><input type="radio" name="exceptionupdate" class="_exceptionupdate" value="No" onclick="ExceptionUpdate()" />No</label> 

Call to getElementsByClassName("class") returns a collection of elements. Iterate over them and clear value in a loop. Use value or other attribute or innerHTML depending on your need:

function clearText() {
    var elements = document.getElementsByClassName("abc");
    [...elements].forEach(element => {
        element.value = "";
        // element.innerHTML="";
    });
}

Instead of [...elements].forEach() you may use Array.from(elements).forEach() .

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