goryef
goryef

Reputation: 1489

HTML table change cell color

I have an HTML table to which i add rows when button is clicked. That part work fine:

function ic_add_supplier_line(){
   var table = document.getElementById("ic_current_pricing");
   var count = $('#ic_current_pricing tr').length;
   var row = table.insertRow(count); 
  for (i = 0; i < 8; i++) {
     var cell = row.insertCell(i); 
     var cell_id = "ic_q_" + String(i) +"_" + String(count)
     cell.innerHTML = "<input id=" + cell_id + " style='width:100%;' type='text' ondblclick='select_supplier(this.id)' >" 
  } 
}

When cell is double clicked I want the cell background color to change.

  function select_supplier(elm_id) {
     var cur_row = elm_id.slice(-1)
     var table = document.getElementById("ic_current_pricing");
     var rows = table.getElementsByTagName("tr") ;
     for (var i=0; i<rows.length; i++) {
        if (i== cur_row){
           for (j =0; j<8; j++){
               rows[i].cells[j].className="on"
           }    
        }else{
           for (j =0; j<8; j++){
           rows[i].cells[j].className=""        
        }
     }
   }
}

and CSS

.on{
   background-color:green ;
 }

Only border/outline is changing color. Cell remains white. Appreciate any help. Thanks in advance.

Upvotes: 1

Views: 1517

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22265

a solution, expect corresponding ?
(more simple to change entire row color _ and ES6 syntax...)

const ic_Table = document.querySelector("#ic_current_pricing tbody")

function ic_add_supplier_line()
  {
  let count = ic_Table.rows.length
   , newRow = ic_Table.insertRow( count )
  for (let i=0; i < 4; i++)   // changed 8 to 4 
    {
    newRow
      .insertCell(i)
      .innerHTML = `<input id="ic_${i}_${count}" type="text" >` 
    } 
  }

ic_Table.ondblclick=e=>  // event delegation for double click for every <input
  {
  if(!e.target.tagName.toLowerCase=='input') return
  let TR_parent = e.target.parentNode.parentNode
  ic_Table.querySelectorAll('tr').forEach(xTR=> xTR.className = (xTR===TR_parent) ? 'on' : '' )
  }

R_plus.onclick = ic_add_supplier_line
table { border-collapse: collapse; margin: 1em }
td { border: 1px solid grey; padding: .5em 0; height: 1em; width:110px; text-align:center; }

td input[type=text] { width:80px !important  }

.on { background-color:green ; }
<button id="R_plus">Add Row</button>

<table id="ic_current_pricing">
  <tbody>
  </tbody>
</table>

Upvotes: 1

Luay
Luay

Reputation: 814

The problem was that the input field generated overlapped the actual cell, so when the color change was occurring it wouldn't display the entire cell since the input field was taking 99% of it. By altering and assigning the "on" class to effect the input fields, we got the final result that OP desired.

Upvotes: 1

Related Questions