Dynamically using jQuery, a table with alternating rows contains a select box in the background color

I have a table with rows that include select boxes. I want to apply alternating colors to the rows, but the select boxes aren't changing color. How can I achieve this?

HTML

<table width="100%" cellpadding="0" cellspacing="0" border="0"
class="stdform">
    ..other codes...
    <tr><td>
    <table class="fancyTable" id="sortable-table"
            cellpadding="0" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <td>header one</td>
                    <td><select><option>--select--</option></select></td>
                    <td>header three</td>
                </tr>
            </thead>
            <tbody id="job-tbody">
                <tr class="prototype">
                    <td>one</td>
                    <td><select><option>--select--</option></select></td>
                    <td>three</td>
                </tr>
            </tbody>
    </table>
    </td></tr>
</table>

CSS:

   $(document).ready(function() {
        $("tr:odd").css("background-color","#eee");
       $("tr:even").css("background-color","#ddd");
    });

FIDDLE: http://jsfiddle.net/wk7Dy/15/

Answer №1

To style the select element separately, you can use the following code snippet. You can also view and test the code on this JSFiddle link.

  $(document).ready(function() {
    $("tr:odd").css("background-color", "#eee");
    $("tr:even").css("background-color", "#ddd");
    $("tr:even").find('select').css("background-color", "#ddd");
    $("tr:odd").find('select').css("background-color", "#eee");
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" cellpadding="0" cellspacing="0" border="0" class="stdform">
  ..other codes...
  <tr>
    <td>
      <table class="fancyTable" id="sortable-table" cellpadding="0" cellspacing="0" width="100%">
        <thead>
          <tr>
            <td>header one</td>
            <td>
              <select>
                <option>--select--</option>
              </select>
            </td>
            <td>header three</td>
          </tr>
        </thead>
        <tbody id="job-tbody">
          <tr class="prototype">
            <td>one</td>
            <td>
              <select>
                <option>--select--</option>
                <option>--select--</option>
              </select>
            </td>
            <td>three</td>
          </tr>
        </tbody>
      </table>
    </td>
  </tr>
</table>

Answer №2

It is generally not recommended to use inline styles, so here is an alternative solution that may be helpful.
Although the answer has already been accepted, I am adding this for reference.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Image change by a</title>

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

  <script>
  $(function() {
    $("tr:odd").addClass("oddrow");
    $("tr:even").addClass("evenrow");
   });
  </script>
  <style>
  .oddrow{background-color:green;}
  .evenrow{background-color:red;}
  .oddrow select{background-color:green !important;}
  .evenrow select{background-color:red}
  </style>
</head>
<body>

 <table width="100%" cellpadding="0" cellspacing="0" border="0"
    class="stdform">
        ..other codes...
        <tr><td>
        <table class="fancyTable" id="sortable-table"
                cellpadding="0" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <td>header one</td>
                        <td><select><option>--select--</option></select></td>
                        <td>header three</td>
                    </tr>
                </thead>
                <tbody id="job-tbody">
                    <tr class="prototype">
                        <td>one</td>
                        <td><select><option>--select--</option></select></td>
                        <td>three</td>
                    </tr>

                </tbody>
        </table>
        </td></tr>
    </table>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS closes when clicked outside

I've been attempting to add a close on outside click functionality to my code, similar to this example: http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview However, I seem to be overlooking something as it's not working in my implementation. HT ...

Issue with onClick event not triggering within echo statement when using AJAX

When inserting the following code snippet into the head section of a page: <script type="text/javascript"> function vote() { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject( ...

Can I safely execute JSON.parse() on the window's location hash?

Is it safe to store JavaScript variables in the URL's hash for web application state restoration through bookmarks? I've been considering using JSON serialization as a method. Storing variables like this: var params = { var1: window.val1, var2: ...

Having trouble retrieving a Controller parameter from a form in ASP.NET MVC?

Currently encountering an issue with a controller that is structured as follows: public class AccountsController:Controller { public ActionResult List(int? page, int? pageSize, string keywords) {...} } The approach we are using to send data to this c ...

Issue with ThreeJs raycaster not returning correct event.clientY value when header bar is visible

Here's the issue: I'm trying to place a sphere on a 3D model when I click on it using ThreeJs raycaster. It works fine when the canvas covers the entire page, but if I add a header bar to the page, the positioning is off. Here are some visual ex ...

In React-router-dom version 5, match.params.id functions properly, but it experiences issues in version 6

Can anyone help me figure out the proper way to achieve this functionality in react-router version 6? When I use console.log with match, it returns undefined, even though it works fine in v5. import React from 'react' const NotePage = ({ match } ...

Position the icon to the left side of the button using Bootstrap

Need help with centering text on a bootstrap 3 button while aligning the font awesome icon to the left side. <button type="button" class="btn btn-default btn-lg btn-block"> <i class="fa fa-home pull-left"></i> Home </button> Usi ...

How can I prevent ng-blur from triggering when ng-readonly is set to true in AngularJS?

I am currently working with AngularJS and have run into an issue when combining ng-blur with ng-readonly. Even though ng-readonly is set to true, ng-blur still triggers (if the input field is clicked and then somewhere else is clicked). In this example, n ...

Setting up Angular 4 with TailwindCSS

Can TailwindCSS be configured with Angular (4+)? I am willing to eject the Angular project in order to make webpack configuration accessible. However, I am uncertain about what needs to be included in the webpack.config.js file to ensure that TailwindCSS ...

Tips for Maintaining Table Headers in Place While Scrolling Through a Table

Check out my jsfiddle: http://jsfiddle.net/7vv9e/2/ In the fiddle, click on the "Add Question" button multiple times until a scroll bar appears next to the table. I am looking to keep the header fixed while scrolling. How can this be achieved? Below is ...

Is there a way to make JavaScript function properly with PHP-generated content?

I have a PHP file that loads a variety of forms depending on an identifier passed through a GET request. Everything is functioning properly, except for my JavaScript/jQuery code. Is there a way I can refresh the JavaScript to make it work with the form? ...

Is there a way to verify the href attribute and potentially append the complete URL address if necessary?

Is there a way to verify the href attribute and replace it with a full URL if it doesn't contain the full path? I tried using JavaScript for this, but it doesn't seem to work on IE 8. This is my JavaScript code: fullUrl = $(this).filter('[ ...

What is the process for triggering a sorted output from my MongoDB database by simply clicking a button?

I'm struggling with sorting my collection by rating in my code. I have this snippet where I'm sending my collection to index.ejs: router.get('/', (req, res) =>{ FILM .find().limit(6) .then(films => res.render(& ...

What is the best way to send multiple values via ajax?

view error screenshot Upon clicking the button, a function is called which returns certain values. These values need to be retrieved and sent via AJAX using jQuery. Below is the function that is called upon clicking the button. Within this function, anot ...

Switching background images for DIVs when links are rolled over

Having trouble changing the background image of a div when a user hovers over a link. Any ideas on what might be causing this issue? <style> #divToSwap { background-image: url(black.jpg); height: 150px; width: 150px; } </style> &l ...

Unable to assign a value to a prop in a Vue component due to a jQuery plugin integration

I have successfully integrated the jquery redactor plugin into a Vue component. While the plugin is functioning as expected, I am facing an issue in accessing the HTML content generated by Redactor within the Vue environment. Despite trying various method ...

Enhancing JQuery Validation by incorporating a bespoke method for submission validation

Once the form is submitted, I need a simple js/jquery function to perform additional validation. My form supports multiple file inputs, and I must ensure that the combined total size of all files does not exceed a predefined file limit. var totalFileSize ...

What are the best practices for effectively managing jQuery UI sliders?

I am currently developing a web application that involves updating jQuery UI sliders using JavaScript. While I have managed to resolve most of the issues related to updating the slider after initialization, there is one particular issue that remains unreso ...

What is the process for triggering a PHP function when a form element is clicked in a webpage?

Currently, I am trying to implement a jQuery colorbox on my webpage which appears over a <select> drop-down list. My goal is to trigger an AJAX call every time a new option is selected from the drop-down. Even though I have written the following cod ...

Ways to segment into a proper array

I received the following object from an API and I am looking to convert it into an array using either JavaScript or C#. [ "1":"h1:first", "2":".content a > img", "3":"#content div p" ] I attempted converting it to a JSON object and using the spl ...