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?

3
  • onclick='foo(i)' change the i values to 1 and 0 in the respective conditions Commented Apr 3, 2017 at 17:53
  • This condition serves no purpose. Commented Apr 3, 2017 at 17:57
  • These are just test cases. Ultimately I will only have one line of document.write(..foo(i) Commented Apr 3, 2017 at 18:00

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

12 Comments

if i==1 then you can also say onclick='foo(1)'
This is the correct way, but then what is the reason for this condition?
or that if condition should be removed
These are just test cases. Ultimately I will only have one line of document.write(..foo(i)
This answer is what I am looking for. Thanks!
|
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";

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.