Amran Amran - 1 month ago 4
HTML Question

Change <td> Background Color After Validation

I have a form inside a table. I want to change the

<td>
background color after form validation for the error. I manage to do it by inserting an if condition on each
<td>
style attribute. Is there a short way.

For example maybe by using jquery. Below is my style of codes:

<td style="<?php echo (!empty($msgError) && empty($purchase_mode)) ? 'background-color: rgba(244, 67, 54, 0.33);' : ''; ?> ">
<input type="checkbox" name="purchase_mode" value="DIRECT"/>Direct
</td>
<td style="<?php echo (!empty($msgError) && empty($purchase_category)) ? 'background-color: rgba(244, 67, 54, 0.33);' : ''; ?> ">
<input type="checkbox" name="description" value="SUPPLY"/>SUPPLY
</td>


I have tried to use jquery but it will change all the
<td>
background color on the table:

<?php if (empty($purchase_category) || empty($purchase_mode)) { ?>
<script>
$(document).ready(function(){
$("td").css("background-color", "red");
});
</script>';
<?php } ?>

Answer

You can create an array of string with all the invalid fields name property and then it will take care to set the background color for those fields:

function ValidateForm(invalidFields){
$("td input").each(function(){
  if($.inArray(this.name,invalidFields) >= 0){
    $(this).parent().css("background-color","rgba(244, 67, 54, 0.33)");
    }
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="checkbox" name="purchase_mode" value="DIRECT" />Direct
    </td>
    <td>
      <input type="checkbox" name="description" value="SUPPLY" />SUPPLY
    </td>
  </tr>
  <tr>
      <td><input type="button" onclick="ValidateForm(['purchase_mode'])" value="Validate Form"></td>
  </tr>
</table>