0

I'm trying to send onclick parameters with html onclick

for (var i = 0; i < 2; i++) {
    if (i == 1) {
        document.write(" <tr class='noBorder' onclick='foo(i)' >");
    }
    if (i == 0) {
        document.write(" <tr class='noBorder' onclick='foo(i)' >");
    }
}

However, whenever I click on a row, I get back onclick = foo(2)

I've been looking around and found the same question

Javascript - Dynamically assign onclick event in the loop

I was wondering if it is possible to do this with document.write?

Community
  • 1
  • 1

2 Answers2

0

You just need to remove ifrom the Javascript String:

for (var i = 0; i < 2; i++) {
    if (i == 1) {
        document.write(" <tr class='noBorder' onclick='foo(" + i + ")' >");
    }
    if (i == 0) {
        document.write(" <tr class='noBorder' onclick='foo(" + i + ")' >");
    }
}

2 Notes

  1. You should inverse your use of ' and "... using '...' to delimit attributes isn't valid HTML5 (you need <div style="..."></div>, not <div style='...'></div>)
  2. You see foo(2) everywhere because that's the last value i had. Your onclick works, but is fetching the last value that i had, instead of hardcoding the value of i when HTML was rendered.
SsJVasto
  • 486
  • 2
  • 13
0

document.write statements must be run before the page finishes loading

Therefore, you wouldn't want to put document.write into an onclick

If you're trying to modify a page already loaded you'll have to use div tags and use something like:

document.getElementById("name").innerHTML = "bob";