1

I am creating a html table by javascript, but I can't set the class name to these elements.

What I want: clicking on the one of the inputs in the second column activates function. For example, this function set the <p> color to red.

I was trying many solutions, but it's still not working.

HTML:

<div id="table"></div> 
<p id="a">adasd</p>

JS:

var arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];

var table = "<table><tr><td><b>Test</b></td>";
table += "<td style='width: 50px'>RN</td>";
table += "<td style='width: 50px'>MW</td></tr>";

for (var i=0; i<arr.length; i++) {
    table += "<td>" + arr[i] + "</td>";
    table += "<td><input class='rn' style='width: 50px'></input></td>";
    table += "<td><input style='width: 50px'></input></td></tr>";
}

table += "</table>";

document.querySelectorAll('.rn').onclick = function() {change()};

function change() {
    document.getElementById("a").style.color = "red";
}
document.getElementById("table").innerHTML = table;
1
  • does the answer solve your problem ? Commented Nov 19, 2017 at 15:41

1 Answer 1

1

You can't run onclick with querySelectorAll, here is my simple solution. I just added onclick='change()'

var arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];

var table = "<table><tr><td><b>Test</b></td>";
table += "<td style='width: 50px'>RN</td>";
table += "<td style='width: 50px'>MW</td></tr>";

for (var i=0; i<arr.length; i++) {
    table += "<td>" + arr[i] + "</td>";
    table += "<td><input class='rn' style='width: 50px' onclick='change()' ></input></td>";
    table += "<td><input style='width: 50px'></input></td></tr>";
}

table += "</table>";


function change() {

    document.getElementById("a").style.color = "red";
}
document.getElementById("table").innerHTML = table;
<div id="table"></div> 
<p id="a">adasd</p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.