Trigger event for each object

I want the site to change the element class if it is full. So, when the user blurleaves the input field, the program checks to see if it has any value, and if so, adds a class. The problem is to pass this behavior to each element in the collection of the class.

var input = document.getElementsByClassName('input');
contentCheck = function(i){
    if(input[i].value>0) input[i].classList.add('filled');
    else input[i].classList.remove('filled');
};
for(var i=0; i<input.length; i++) {
    input[i].addEventListener('blur',contentCheck(i));
}

This works once after reloading the page (if there is any content in the cache), but contentCheck()should start every time you leave focus.

+4
source share
2 answers

" , , this contentCheck ( ):

var input = document.getElementsByClassName('input');
var contentCheck = function(){ // <== No `i` argument (and note the `var`)
    // Use `this` here
    if(this.value>0) this.classList.add('filled');
    else this.classList.remove('filled');
};
for(var i=0; i<input.length; i++) {
    input[i].addEventListener('blur',contentCheck);
    // No () here -------------------------------------^
}

: classList toggle, :

var contentCheck = function(){
    this.classList.toggle('filled', this.value > 0);
};

" " ( , , ), contentCheck , :

var input = document.getElementsByClassName('input');
var makeContentCheckHandler  = function(i){
    return function() {
        if(input[i].value>0) input[i].classList.add('filled');
        else input[i].classList.remove('filled');
    };
};
for(var i=0; i<input.length; i++) {
    input[i].addEventListener('blur', makeContentCheckHandler(i));
}

. , .

+4

input[i].addEventListener('blur',function(e){
 console.log(e);
});

: https://jsfiddle.net/42etb4st/4/

0

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


All Articles