Andrew Tran
Andrew Tran

Reputation: 57

Is there anyway to highlight number of cells of a html table base on user input? Javascript

for example I have a integer html table with 5 rows and 5 columns from 1 to 25

I will let the user input the number of cells they want to highlight. when they input something like 5. How can I highlight the first row and the next 2 cells. And what if the user click the button "right arrow" How can I highlight the next cell and row that total 5 cells? I am new to Javascript. Sorry If my English isn't explained so good.

Upvotes: 0

Views: 89

Answers (1)

Mister Jojo
Mister Jojo

Reputation: 22353

this way

const
    TableX = document.body.appendChild(document.createElement('table'))
  , formEl = document.querySelector('form')
  , HighLighting = 
    { rc1 : 0
    , rcN : 0
    , setColor( hightLight )
      {
      for (let rc=this.rc1; rc<this.rcN; ++rc )
        {
        let r = Math.floor(rc / 5) 
          , c = (rc % 5) 
          ;
        TableX.rows[r].cells[c].classList.toggle('highLight', hightLight)
        }
      }
    }
formEl.onsubmit = e =>
  {
  e.preventDefault()
  HighLighting.setColor(false)
  HighLighting.rc1 = formEl['cell-first'].valueAsNumber -1
  HighLighting.rcN = Math.min((HighLighting.rc1 + formEl['cell-count'].valueAsNumber) , 25 )
  HighLighting.setColor(true)
  }
for( let r=0;r<5;++r) // make Table rows ¹& cells
  { 
  let newRow = TableX.insertRow()
  for(c=0;c<5;++c)
    { 
    newRow.insertCell().textContent = r*5 + c +1 
    }
  }
table  {
  border-collapse : collapse;
  margin          : 2em 1em;
  }
table td {
  padding    : .2em .8em;
  border     : 1px solid darkblue;
  text-align : center;
  cursor     : pointer;
  }
form { margin: 1em; }
input[type="number"] { width: 5em; }

.highLight { background-color: yellow; }
<form>
  <p> first cell : <input name="cell-first" type="number" min="1" max="25" value="1" required> </p>
  <p> cell count : <input name="cell-count" type="number" min="1" max="25" value="1" required> </p>
  <button type="submit">highLight !</button>
</form>

Upvotes: 1

Related Questions