简体   繁体   中英

jQuery for setting background color in asp repeater based on changed value of a dropdownlist

I have a repeater in my asp.net web page that contains a table with rows. There are several textboxes, dropdowns and other fields in a row. What I want is that when a value of one of my dropdowns in my repeater row changes, that the whole table row gets a color. I managed to do this server-side, but I want it client-side.

Here's my code:

HTML

<table id="InvoerUrenTable" class="InvoerUrenLeftMargin100">    
<asp:Repeater ID="urenRepeater" runat="server">
    <ItemTemplate>
        <tr runat="server" ID="itemTemplateRow">
            ...
            ...
            ...
            <td >
                <asp:DropDownList runat="server" ID="projectDropDown" ></asp:DropDownList>
            </td>
            ...
            ...
            ...
            ...
        </tr>
    </ItemTemplate>
</asp:Repeater>
</table>
<script type="text/javascript">
      $(document).ready(function () {
          $('#projectDropDown').change(function () {
              var index = $(this).parent().children().index($(this));
              $('#urenRepeater tr:nth-child(' + index + ')').addClass("highlight")    
          });
      });
</script>

CSS

.highlight {
background-color: #E52718;
}

The above script doesn't seems to work. What am I doing wrong?

UPDATE 06/07/2020

I found out I was selecting the wrong row id to change the class.

  <script type="text/javascript">
      $(document).ready(function () {
          $('.projDropDown').change(function () {
              var index = $(this).parent().children().index($(this));
              $('#body_urenRepeater_itemTemplateRow_' + index).addClass("highlight")    
          });
      });
  </script>

Now is the problem that my index is wrong, it marks everytime the first row if I change the value of one of my dropdowns.

Since the dropdown is in a repeater - and can therefore potentially be copied multiple times in the final page -, it will either end up with a different ID in the rendered HTML (if asp.net attempts to make the IDs unique in the browser), or you'll end up with multiple dropdowns with the same ID (which is invalid). Either way you've got problems because the jQuery code can't identify the correct one to target.

I suggest using a CSS class as your selector instead. That won't get altered by the asp.net rendering engine, and it also will allow you to target multiple elements with one event handler.

eg

<asp:DropDownList runat="server" ID="projectDropDown" CssClass="projDropDown" ></asp:DropDownList>

and

$('.projDropDown').change(function () {

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