The JavaScript OnChange function fails to work the second time around

I am trying to implement an HTML table with td cells that can change background color from red to green ("C" to "A") and from green to red ("A" to "C") using the "select onchange" event. The issue I am facing is that it works the first time but not the second time.

Below is the JavaScript code:

<script type="text/javascript">
function changeColor(id){
var cell=document.getElementById(id);
cell.style.backgroundColor="#e50017";//red
}
function exchangeColor(id){
var cell=document.getElementById(id);
cell.style.backgroundColor="#009900";//green
}
</script>

And here is the HTML structure:

<form id="menuForm" name="menuForm" >
<table summary="layout table">
<tbody></br>
<tr>
           <td rowspan="1" colspan="1" id="prova" width="35px" align="center" bgcolor="#e50017">
            M
            <br>
            <select onchange="exchangeColor('prova')" name="select1">
            <option value="0" selected="selected">C</option>
            <option value="1">A</option>
            </select>
            </td>
            <td rowspan="1" colspan="1" id="prova1" width="35px" align="center" bgcolor="#009900">
            M
            <br>
            <select onchange="changeColor('prova1')" name="select2">
            <option value="1" selected="selected">A</option>
            <option value="0">C</option>
            </select>
            </td>
        </tr>
      </tbody>
    </table>     
</form>

Answer №1

My suggestion would be to utilize toggling class names instead. This approach offers simplicity and flexibility, allowing you to easily modify not just the background color but any other styles without needing to make changes directly in the JavaScript function:

function switchColor(id) {
    var element = document.getElementById(id);
    element.className = element.className === 'red' ? 'green' : 'red';
}
.red {
    background: #e50017;
}
.green {
    background: #009900;
}
<form id="menuForm" name="menuForm">
    <table summary="layout table">
        <tbody>
            <tr>
                <td rowspan="1" colspan="1" id="prova" width="35px" class="red" align="center">M
                    <br>
                    <select onchange="switchColor('prova')" name="select1">
                        <option value="0" selected="selected">C</option>
                        <option value="1">A</option>
                    </select>
                </td>
                <td rowspan="1" colspan="1" id="prova1" width="35px" class="green" align="center">M
                    <br>
                    <select onchange="switchColor('prova1')" name="select2">
                        <option value="1" selected="selected">A</option>
                        <option value="0">C</option>
                    </select>
                </td>
            </tr>
        </tbody>
    </table>
</form>

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

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

What steps do you take to establish a relay connection for pagination in an ORM framework?

After thorough research of Relay's documentation, I have yet to find a clear explanation on how to establish a Relay connection with an ORM. The examples provided mainly utilize the connectionFromArray method, which works well for data stored in memor ...

Adding additional information using Mongoose leads to enhanced output in Handlebars

Imagine having a function that identifies all open bets in a specific collection: app.get('/profile/bet-history', function(req, res, next){ var user = req.user; if(user){ Bet.find({$query : {"username" : user.username ...

Looking into the field of a document that is referenced

Within the database, there are two collections: 'actors' and 'movies' Here is an example of one actor: { _id: ObjectId("54f38bd9b814dca762778032"), name: { first: 'Jason', last: 'Statham' } } And her ...

What is the purpose of assigning scope.property to scope.property() in order for the expression to function properly?

I have encountered an interesting situation with the directive below. In order for my expressnum function to work in the template, I had to include the line scope.expressnum = scope.expressnum();. It does what I need it to do, but I'm not entirely sur ...

Having trouble choosing an item from the Select2 drop-down menu

I have been developing an application that incorporates Select2 (version 3.5.1). The HTML used to create the dropdown / autocomplete field is as follows: <input id="mySelect" class="form-control" type="hidden"> The snippet above includes the form-c ...

What is the best way to ensure a jQuery UI slider recognizes when the mouse is released after being clicked?

I have integrated the jQuery slider into my application and am facing an issue with triggering an event to update the database upon releasing the slider. Currently, I am using the following code snippet: $('.ui-slider-handle').mouseup(function () ...

ES6 Babel's grammar is set to be exported as the default

When using Babel, I am encountering an issue with importing the module shown below: // mongoose_helpers.js const r_string = { type: String, required: true } const r_number = { type: Number, required: true } export default { r_string, r_number } ...

The AngularJS ngModelController is a powerful tool for managing

How can I accurately check ngModelController validity? Within my directive, I have a controller object. When I console.log the object from inside the directive, it displays: console.log(ctrl) $dirty: false $invalid: true $modelValue: "" $name: undefined ...

Leveraging trustAsHTML with an array of object elements

I'm facing a challenge in passing an array of objects from an Angular Controller to the ng-repeat directive. The objects within the array have multiple properties, some of which may contain HTML that needs to be displayed using the ng-repeat. I' ...

Creating head tags that are less bouncy

After running my code, I noticed that the headlines didn't transition smoothly - they seemed to jump rather than flow seamlessly. To address this issue, I attempted to incorporate fadeIn and fadeOut functions which did improve the smoothness slightly. ...

What is the proper way to search for a specific string within a JavaScript array during an iteration?

I am working with an array that is continuously updated with new string elements every 2 seconds. The code snippet below showcases how the updates are processed: //tick world setInterval(function(){ doTradeUpdate(); },5000); function doTradeUpdate(){ ...

`When you extend a $resource object, it effectively removes the prototype from the

Here's the current code snippet I'm working with: // Factory angular.factory('Student', function() { var defaults = { StudentId: null }; var Student = function(params) { angular.extend(this, angular.copy(de ...

No receiving a callback_query update upon user pressing an inline button in the Telegram webhook

When using the node-telegram-bot-api library, I encountered an issue with my Webhook. Although I am able to receive updates when messages are sent, I do not get any updates when a user presses a button in an inline keyboard. class BotController { async ...

Where is the best place to implement HTML form validation: on the frontend or backend?

Is it important to validate all values before submitting the form to the backend server, as mentioned in the title? ...

Pulling a WooCommerce variable in PHP: A guide for JavaScript developers

I'm having some trouble executing PHP code that utilizes the WooCommerce variable to retrieve the order ID. add_action('add_meta_boxes', 'gen_order_meta_boxes'); function gen_order_meta_boxes() { add_meta_box( 'wo ...

Using HTML5 data attributes as alternative configuration options in a jQuery plugin can present challenges

I am currently in the process of creating my very first jQuery plugin, and I have encountered a challenge when attempting to extend the plugin to support HTML5 data attributes. The idea is for a user to be able to initialize and adjust settings simply by u ...

The TypeScript compiler does not allow a 'number' type to be assigned to 0, 10, or 20, even when the number itself is 0

When testing out my code snippet on the playground for Typescript, an error appears on line 24. I discovered that the issue can be resolved by explicitly casting commands back to <IPlan[]>, but I wonder why this extra step is necessary. Property &a ...

Guide to display half of an image and allow for full image viewing upon mouse hover

After creating my bootstrap 4 website, I encountered an issue with the code below where only half of the image is displayed initially due to a conflict in the code. It also fails to work properly when moving the mouse after shifting the whole image from ri ...