Skip to content
Advertisement

How to make adjacent col’s input field mandatory based on a selection in another column/same row HTML Table?

There’s quite a few examples around, but I couldn’t find one covering a table. The intent is to have the Comments column’s input field shown as mandatory, if value Rejected or Discuss is selected in an adjacent column.

Here’s a Fiddle

I’ve seen that there should be an onchange added to each row of the table, which would call a function, but there should be an id for each row?

This is how I’m building the table, using GAS:

function createTable(dataArray) {
  if (dataArray && dataArray !== undefined && dataArray.length != 0) {
    var option = "<select name='D1'>" +
      "<option value='empty'></option>" +
      "<option value='Approved'>Approved</option>" +
      "<option value='Discuss'>Discuss</option>" +
      "<option value='Rejected'>Rejected</option>" +
      "</select>";
    var textBox = "<input type='text' name='comments'/>"

    var result = "<div class='card'><table class='table table-borderless table-hover' id='dtable'>" +
      "<thead style='white-space: nowrap'>" +
      "<tr>" + //Change table headings to match witht he Google Sheet
      "<th class='text-center'>Notes</th>" +
      "<th class='text-center'>Approval</th>" +
      "<th class='text-center'>Comments</th>" +
      "</tr>" +
      "</thead>" +
      "<tbody>";
    for (var i = 0; i < dataArray.length; i++) {
      result += "<tr>";
      for (var j = 0; j < dataArray[i].length; j++) { //Checks if Link columns has data and pushes it as a link into the table
        result += "<td class='align-middle' style='word-wrap: break-word;max-width: 160px;text-align:center'>" + dataArray[i][j] + "</td>";
      }
      result += "<td class='align-middle' style='text-align:center'>" + option + "</td>";
      result += "<td class='align-middle' style='text-align:center'>" + textBox + "</td>";
      result += "</tr>";
    }
    result += "</tbody></table></div><br>";
    var div = document.getElementById('search-results');
    div.innerHTML = result;
  } else {
    var div = document.getElementById('search-results');
    div.innerHTML = "Data not found!";
    return;
  }
}

Appreciate your help!

Advertisement

Answer

Add onChange event for select box like selectValueChanged and then inside the method pass the current object. Using current object , find the selected value and then perform your operations.

function selectValueChanged(cur){
    if(cur.value == "Rejected" || cur.value == "Discuss"){
    cur.parentElement.nextElementSibling.children[0].required = true;
    cur.parentElement.nextElementSibling.children[0].placeholder = "this is requred";
  }else{
    cur.parentElement.nextElementSibling.children[0].required = false;
    cur.parentElement.nextElementSibling.children[0].placeholder = "Optional";
  }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement