How to add a function in js to a html element – which only made in js?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to add a function in js to a html element – which only made in js? on this date .

I would like to change a row’s background-color in a table, if I select an object of a “select”‘s list, but only if this element, which is a number is even. But the main problem is that the “object” is made in js, so that is not in the html file, so I couldn’t add to the objects an onclick function, which could make the background-color of the row change. Please help, I’ve lost.

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

It seems that you are working with JQuery. You can do it with plain JS or with JQuery.

JQuery

It is advised to work with the change event instead of a click event. The change event however will only trigger on a change. I will do it with the change for this.

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");
}

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";
  });
}