João Silva João Silva - 1 month ago 10
Javascript Question

jquery add event to cells into a board

How can I add an event to cells inside a board?
I have a grid of 9x9 and I want to add an event to them, for exemple, this is part of my grid in HTML:

<div class="container">
<div class="dad-board">
<div class="dad-row">
<div class="dad-cell">
<input type="number" data-column="0" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="1" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="2" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="3" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="4" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="5" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="6" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="7" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="8" data-line="0">
</div>
...
</div>
</div>


Now im jquery I wanted to do something like this:

(function() {
'use strict'


$('#dad-board > dad-cell').focusout(function(){

if($(this).text()>0 && $(this).text()<10){

$(this).addClass('with-value');
}else{
$(this).removeClass('with-value');
}

});
}());


Thank you in advance for the help.

Answer

Two things:

In $('#dad-board > dad-cell') the class name should be .dad-cell.

.dad-cell are div and as such them don't have a focusout event. I think you meant $('#dad-board > .dad-cell input').

In order to make your current code work, you'll also have to make some adjustments:

$('#dad-board > .dad-cell input').focusout(function(){
    //as we're talking about input fields, the value is read with val(), not text()
    //and as you're gonna evaluate it as an integer, lets convert the value to integer
    var value=parseInt($(this).val());       
    if(!isNaN(value)&&value>0 && value<10){
        //you might want to set with-value to the <div>, not the input
        $(this).parent().addClass('with-value');
    }else{
        //you might want to set with-value to the <div>, not the input
        $(this).parent().removeClass('with-value');
    }
});
Comments