简体   繁体   中英

How to change the color of table cells based on a string?

I want my table row to change its color depending its dropdown status. How to do this using ajax?

echo '<table id="table_id">';
echo '<tr>';
echo '<td><b>'.$client.'</b></td>';
echo '<td>
<select class="color_status" onchange="update_Status(this.value)">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Yellow">Yellow</option>
</select>
</td>';
echo '</tr>';
echo '</table>';

If I will select a red in the dropdown the current row cell will change its color.
I did something like this on script:

function update_Status(str){
     if(str=='Red'){
       //the current row cells will turn to red
     }
     if(str=='Green'){
       //the current row cells will turn to green
     }
     if(str=='Yellow'){
       //the current row cells will turn to yellow
     }
}

This might be a little simplistic and may need to be updated for your specific application but given the sample code you have shown this seems to work.

You can look for the parent node of the dropdown and then get the sibling td and change it backgroundColor using the element value directly. You do need to pass the element instead of just the value update_Status(this) instead of update_Status(this.value) as you need to find the parent and sibling starting from the element.

Assuming the following HTML:

<table id="table_id">
    <tr>
        <td><b>'.$client.'</b>
        </td>
        <td>
            <select class="color_status" onchange="update_Status(this)">
                <option value="Red">Red</option>
                <option value="Green">Green</option>
                <option value="Yellow">Yellow</option>
            </select>
        </td>
    </tr>
</table>

This will do what you need I think:

function update_Status(list) {
    var cell = list.parentNode;

    var targetCell = cell;

    do targetCell = targetCell.previousSibling;
    while (targetCell && targetCell.nodeType != 1);

    targetCell.style.backgroundColor = list.value;
}

// I'm assuming if you got many rows with this dropdown you would need to iterate through result of getElementsByClassName to execute onchange on each one.
document.getElementsByClassName('color_status')[0].onchange();

DEMO - Find sibling td and change backgroundColor



Multi-Row DEMO


Currently some browser engines insert TextNodes for white spaces, therefore previousSibling may not actually return the td the first time it is called. TextNodes are of type 3 and you want to make sure your finding a ElementNode, which is type 1. That is why we loop until previousSibling returns a node type 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM