elstiv elstiv - 3 months ago 10
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:

<script>

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";
}
else{
textbx.style.backgroundColor = "";
textbxsur.style.backgroundColor = "";
}
}

changeBack();

</script>


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

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

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <table>
        <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Status</td>
        </tr>
        <?php for($i=1; $i<4; $i++) { ?>
        <tr>
            <td><?= $i ?></td>
            <td><?= 'Name'.$i ?></td>
            <td><select><option value="p">Present</option><option value="a">Absent</option></select></td>
        </tr>
        <?php } ?>
    </table>
<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') {
                $(this).css('background-color','#F00');
                $(this).parent().parent().css('background-color','#F00');
            } else {
                $(this).css('background-color','#FFF');
                $(this).parent().parent().css('background-color','#FFF');
            }
        });
    });
</script>
</body>
</html>