What is the procedure for adding a JavaScript function to an HTML element that was exclusively created in JavaScript?

I am trying to dynamically change the background color of a row in a table when selecting an object from a dropdown list, but only if the selected number is even. The challenge I am facing is that the objects are created using JavaScript and not directly in the HTML file, so adding an onclick function to each object is not feasible. Please assist me with a solution as I am stuck.

HTML:

        <select class = "form-select, col-6" id="quantiti" onclick = "ifSelectedLetHeadChange()" >
        <!--
        This was the original version that I copied:
        <select class="form-select, col-6" id="quantiti" 
        onclick="ifSelectedLetHeadChange($(this).val())">
        -->
        </select>

JS:

        function quantity(amount) {
                var select = document.getElementById('quantiti');
            for (var i = 0; i < amount; i++) {
            select.options[select.options.length] = new Option(i + 1, i);
                select.options[select.options.index] = i+1 ;
                select.options[select.options.onclick]="ifSelectedOptionLetTrChange()";
            }
        }
        quantity(10000);

        function ifSelectedOptionLetTrChange(value) {
            if (option.value % 2 ) {
                $("tr").css("background-color", "lightblue");
        } else {
                $("tr").css("background-color", "blue");
            }
        }

Answer №1

If you are working with JQuery, there is an option to use plain JS or continue with JQuery for your task.

Using JQuery

In this case, it is recommended to utilize the change event instead of a click event. The change event will specifically trigger when a change occurs. Below is an example using the change event:

var select = $("#quantiti");
var tr = $("tr");

select.on('change', function() {
  var value = $(this).val();
  setTrColor(value);
});

function setTrColor(value) {
  tr.css("background-color", value % 2 ? "lightblue" : "blue");
}

Using Javascript

var select = document.getElementsById("quantiti");
var tr = Array.prototype.slice.call(document.getElementsByTagName("tr"));

select.addEventListener("change", function(event) {
  var targetElement = event.target || event.srcElement;
  var value = targetElement.value;
  setTrColor(value);
});

function setTrColor(value) {
  tr.forEach(function(element){
    element.style.backgroundColor = value % 2 ? "lightblue" : "blue";
  });
}

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

Launching a web application directly from a USB drive

Exploring the world of Javascript frameworks and nodejs, I recently encountered a unique requirement that got me thinking about their practical application. The requirements are as follows: --I need to create a lightweight website that can be run from a U ...

Develop a CakePHP CRUD view using a JavaScript framework

Creating a CRUD view in Cake PHP is simple with the following command: bin/cake bake all users This command builds the users table for CRUD operations. Is there a JavaScript framework that offers similar simplicity? ...

Should I include one of the dependencies' dependencies in my project, or should I directly install it into the root level of the project?

TL;DR Summary (Using Lodash as an example, my application needs to import JavaScript from an NPM package that relies on Lodash. To prevent bundling duplicate versions of the same function, I'm considering not installing Lodash in my application' ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

Is there a way to turn off Emmet's CSS Abbreviations feature in Sublime Text 2?

One thing I really enjoy is how Emmet can generate HTML using 'CSS-like' strings. However, I prefer not to use their CSS Abbreviations. For example, when I write the following line of CSS: li a| I expect to get a tab when I press 'TAB&apos ...

Issue with error handling not being triggered when calling SAPUI5 function()

IBAN validation within a SAPUI5 Wizard is causing some issues for me. I am utilizing a functionImport on a V2 ODataModel (sap.ui.model.odata.v2.ODataModel) to perform this validation. Despite receiving a 202 status code, the request actually failed. Here ...

What is the best way to create a border that surrounds a collection of pictures?

I'm currently facing a challenge in getting a border to perfectly fit around a collection of images. The issue can be observed in this Jsfiddle I shared, where the border aligns with the top and left edges, but not with the bottom and right edges. Her ...

Align an image in the center vertically within a left-floated div with a minimum height

I am currently attempting to vertically align an image within a div that is positioned to the left, and has a minimum height of 150 pixels. The issue I am facing is that none of my attempts seem to be successful. I have tried various methods, including ut ...

Height of Hover Background Color in WordPress Menu

Greetings! Welcome to my website I'm in the process of modifying the hover color for the top menu, and I've managed to change it successfully. However, I would like the hover effect to cover the entire height of the menu, as right now it's ...

Angular - remove elements from an array within a directive when encountering a source error

If an image does not exist, I need to remove the item and push the next one inside ng-repeat. Currently, I am using a custom directive called "noImage". myApp.directive("noImage", function() { return { link: function(scope, element, attrs) { ...

Client-Side Isomorphic JS: A Guide to Using HTTP Requests

Seeking advice on data population for isomorphic flux apps. (Using react, alt, iso, and node but principles are transferable) In my flux 'store' (), I need to fetch data from an api: getState() { return { data : makeHttpRequest(url) ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

"Collaborative Drive" assistance within Google Apps Script

Currently, I am developing a JavaScript tool within Google Apps Script to analyze various document properties such as the validity of links and correct permissions settings. To achieve this, I have been utilizing the API outlined in https://developers.goog ...

Any ideas on how to potentially establish a default route based on conditions with react-router-dom v6?

Managing two pages, Page1 and Page2, requires conditional configuration for setting one as the homepage based on a specific condition. Additionally, all URLs must be prefixed with an ID. Take a look at the code snippet below: <Routes> <Route pat ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...

What steps can I take to ensure my header image adjusts properly for different screen sizes?

Currently, I am working on creating a website for a friend using an exquisite premium Wordpress theme. Despite having paid for the theme, the designer is unwilling to assist with customization. You can view the site in progress at www.zerocarbonfood.co.uk ...

What is the best way to automatically assign a class attribute to all form widgets in Django?

Whenever I create a form using Django, I want the input tag to automatically include a specific CSS class (form-control). Currently, I have to manually add lines of code in my forms.py file for each field like this: class InsertItem(forms.ModelForm): ...

Adjust the background color of a non-selected Material-UI checkbox

Currently, I am working with a combination of React-Redux and Material-UI to style my project. Within this setup, I have a checkbox component that is placed on a toolbar with a blue background color (#295ED9). So far, I have successfully altered the color ...

What is the best way to modify an array within separate functions in a NodeJS environment?

I am facing an issue where I want to update an object inside the fetchAll() functions and then send it back after successful updation. However, the response I receive is '[]'. var ans = [] Country.fetchAll(newdate,(err, data) => { if ...