What is the simple Javascript equivalent of .each and $ (this) when used together, as in this example?

What is the equivalent of a simple Javascript .each, and $(this).findwhen used in this example?

$(document).ready(function(){

    $('.rows').each(function(){
        var textfield = $(this).find(".textfield");
        var colorbox = $(this).find(".box");

            function colorchange() {
                if (textfield.val() <100 || textfield.val() == null) {

                    colorbox.css("background-color","red");
                    colorbox.html("Too Low");
                    }

                else if (textfield.val() >300) {

                    colorbox.css("background-color","red");
                    colorbox.html("Too High");
                    }

                else {

                    colorbox.css("background-color","green");
                    colorbox.html("Just Right");
                    }
                }
            textfield.keyup(colorchange);
        }

)});

Here is the fiddle basically what I am trying to execute, I know that I need to use a loop. I'm just not sure how to set it up. I don't want to use jquery just for this simple function, if I don't need

http://jsfiddle.net/8u5dj/

I deleted the code that I already tried because it changed every instance of colorbox, so I'm not sure what I did wrong.

+4
source share
2 answers

Here's how to do it in plain javascript:

http://jsfiddle.net/johnboker/6A5WS/4/

var rows = document.getElementsByClassName('rows');

for(var i = 0; i < rows.length; i++)
{
    var textfield = rows[i].getElementsByClassName('textfield')[0];
    var colorbox = rows[i].getElementsByClassName('box')[0];

    var colorchange = function(tf, cb)
    { 
        return  function() 
        {
            if (tf.value < 100 || tf.value == null) 
            {
                cb.style.backgroundColor = 'red';
                cb.innerText = "Too Low";
            }
            else if (tf.value > 300) 
            {
                cb.style.backgroundColor = 'red';
                cb.innerText = "Too High";
            }
            else 
            {
                cb.style.backgroundColor = 'green';
                cb.innerText = "Just Right";                    
            }               
        };
    }(textfield, colorbox);

    textfield.onkeyup = colorchange;    
}   
+1
var rows = document.querySelectorAll('.rows');
for (var i=0; i<rows.length; i++) {
    var row = rows[i];
    var textfield = row.querySelector('.textfield');
    var colorbox = row.querySelector('.box');
    // ...
}

, for , querySelectorAll() , . , , .forEach() .

+2

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


All Articles