elstiv elstiv - 1 year ago 67
PHP Question

Change textbox background colour according to value in dropdown

I have a form with textboxes and dropdown for each row. I would like to change the background colour of the textboxes of that particular row when I select 'Absent' from the dropdown of the relative field. I am using javascript which works fine but only with the first row:


function changeBack() {
var inputVal = document.getElementById("attendance_status");
var textbx = document.getElementById("stname");
var textbxsur = document.getElementById("stsurname");
if (inputVal.value == "0") {
textbx.style.backgroundColor = "red";
textbxsur.style.backgroundColor = "red";
textbx.style.backgroundColor = "";
textbxsur.style.backgroundColor = "";



The table is being generated via php as follows:

$query = ("SELECT * FROM `b10_18591250_JC`.`STUDENT` WHERE `ST_GROUP` = $st_group");
$result = mysql_query($query);

while( $row = mysql_fetch_array($result))


echo "<tr>";
echo "<td>" . "<input name=stid[] readonly type=number class=form-control value=" .$row['ID']." </td>";
echo "<td>" . "<input name=stname id=stname readonly type=text class=form-control value=" .$row['NAME']." </td>";
echo "<td>" . "<input name=stsurname id=stsurname readonly type=text class=form-control value=" .$row['SURNAME']." </td>";

echo "<td>";
echo "<select class=form-control name=attendance_status[] id=attendance_status onchange='changeBack()'>";
echo "<option value=1>Present</option>";
echo "<option value=0>Absent</option>";
echo "</select>";

echo "</td>";
echo "</tr>";


Answer Source

Here is a sample using jquey, may be useful for you :

<!DOCTYPE html>
        <?php for($i=1; $i<4; $i++) { ?>
            <td><?= $i ?></td>
            <td><?= 'Name'.$i ?></td>
            <td><select><option value="p">Present</option><option value="a">Absent</option></select></td>
        <?php } ?>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('select').change(function() {
            if($(this).val() == 'a') {
            } else {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download