David Yap
David Yap

Reputation: 7

Using a variable for getElementById

I have a checkbox that is being echoed by PHP. So, the id of the checkbox will be dynamic.

So, I would like use a variable for document.getElementById().

Below is my PHP code:

echo "<td><input type='checkbox' name='edit$count' value='1' onclick='test($count)'></td>";

Then here is my Javascript code

function test(v)
    {
        var edit = "edit" + v;


        if(document.getElementById(edit).checked==true){
            alert(edit);
        }
    }

However, when I clicked on the checkbox, there is no alert.

Is there something wrong with my code?

Upvotes: 1

Views: 3309

Answers (2)

David G
David G

Reputation: 96800

Either replace document.getElementById with document.getElementsByName[] or change your name attribute in your HTML to ids. You're not using id attributes in your HTML which is why getElementById is returning null:

if (document.getElementsByName(edit)[v].checked == true) { ... }

You also don't need the == true as the boolean context of the if statement will take care of it:

if (document.getElementsByName(edit)[v].checked) { ... }

Upvotes: 2

Daniil
Daniil

Reputation: 5780

The answer is because you seted name of the input, and then trying to get it by id. Change name='$count' to id='$count'. And for the future: almost any browser provide Developer Tools with debugger, please, feel free to use it to investigate JavaScript problems.

Upvotes: 0

Related Questions