Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the plain Javascript equivalent of .each and $(this) when used together like in this example?

What is the plain Javascript equivalent of .each and $(this).find when used together 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's a fiddle with basically what I'm trying to accomplish, I know I need to use a loop I'm just not sure exactly how to set it up. I don't want to use jquery just for this simple functionality if I don't have to

http://jsfiddle.net/8u5dj/

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

like image 319
Muskogeee Avatar asked Oct 01 '22 15:10

Muskogeee


1 Answers

This is how to do what you want 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;    
}   
like image 189
John Boker Avatar answered Oct 05 '22 12:10

John Boker