javascript - Highlighting a <td> if two select inputs share a value? -
we've got form has several uniquely named elements; of these elements share same group of options (incl. name/id etc). problem is, need alert user warning (i.e; asterisk, or td turning background-color red) if 2 selectors set same option.
so quick example, might have 2 different selectors;
<select name="servicename-1"> ...options.. </select> <select name="servicename-2"> ...options.. </select>
the options share ids , names. in short, if servicename-n shares selected option id other servicename-n, need perform action - changing td colour, or making div asterisk in visible.
here's more dynamic solution:
- get selects on page, store , loop through them
- see how many of selects have same value current one
- when there more 1 same value, update color of parent
<td>
, otherwise, make white.
you can run following snippet see in action.
$(function() { markduplicates(); }); $("select").on("change", function() { markduplicates(); }); function markduplicates() { //get selects on page , store collection var selectedvalues = $("select"); //loop through selects selectedvalues.each(function() { color = "#fff"; //set default background color current select (white) var value = this.value; //store current selected value //get selects match current value var dupes = selectedvalues.filter(function() { return this.value === value; }); //if there's more 1 selected value have new color td if (dupes.length > 1) { var color = dupes.find("option").filter(function() { return this.value === value; }).attr("data-color"); //get value data-color selected value } //get closest td , set background color dupes.closest("td").css("backgroundcolor", color); }); }
td { height: 50px; width: 50px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <td> <select name="servicename-1"> <option data-color="#f00">one</option> <option data-color="#0f0">two</option> <option data-color="#00f">three</option> </select> </td> <td> <select name="servicename-2"> <option data-color="#f00">one</option> <option data-color="#0f0">two</option> <option data-color="#00f">three</option> </select> </td> <td> <select name="servicename-3"> <option data-color="#f00">one</option> <option data-color="#0f0">two</option> <option data-color="#00f">three</option> </select> </td> <td> <select name="servicename-4"> <option data-color="#f00">one</option> <option data-color="#0f0">two</option> <option data-color="#00f">three</option> </select> </td> </tr> </table>
Comments
Post a Comment