Reputation: 476
I have a password vault being served from a server for a special page on our intranet at work, but I'm having issues passing the ID through the edit()
function into my script. Here is the applicable markup (as you can see it is contained in a PHP
array. Everything, including the id
is being served correctly (ie the ids at the source will read n1
or p7
etc...)):
<tr id='$OTHERInfo[0]'>
<td id='n$OTHERInfo[0]' onclick='edit(this)' contentEditable='false'>$OTHERInfo[1]</td>
<td id='u$OTHERInfo[0]' onclick='edit(this)' contentEditable='false'>$OTHERInfo[2]</td>
<td id='p$OTHERInfo[0]' onclick='edit(this)' contentEditable='false'>$OTHERInfo[3]</td>
<td id='d$OTHERInfo[0]' onclick='edit(this)' contentEditable='false'>$OTHERInfo[4]</td></tr>
Here is the script...it's very simple (it is contained at the bottom of the document):
<script>
function edit(id){
document.getElementById(id).style.backgroundColor = "white";
document.getElementById(id).style.color = "black";
document.getElementById(id).setAttribute("contentEditable", "true");
}
</script>
In the console the error message reads:
Uncaught TypeError: Cannot read property 'style' of null
So obviously the ID is not getting passed correctly, but I don't know what to do. I've also tried just trying to "hard code" the ID into the function in the onclick
like this: edit(n$OTHERInfo[0])
but I have the same issue.
Upvotes: 0
Views: 78
Reputation: 4081
'this' is the entire <td>
element not just its id, so your script should read:
<script>
function edit(element){
element.style.backgroundColor = "white";
element.style.color = "black";
element.setAttribute("contentEditable", "true");
}
</script>
Upvotes: 4
Reputation: 426
<td id='n$OTHERInfo[0]' onclick='edit(this)' contentEditable='false'>$OTHERInfo[1]</td>
If you pass this
to edit
function, you will use the entire element(i.e. the <td>
element) as the parameter rather than its id.
You could try onclick='edit(this.id)'
. This will give you the id of the <td>
element as parameter.
Upvotes: 1
Reputation: 2664
You are providing edit(this)
. The keyword this
references the actual element. It doesn't reference the ID of the element. You can revise your code without document.getElementById
to work.
function edit(element) {
element.style.backgroundColor = "white";
element.style.color = "black";
element.setAttribute("contentEditable", "true");
}
Upvotes: 1
Reputation: 1
id
at edit
function is a reference to the clicked element
onclick='edit(this.id)'
or
function edit(id){
id.style.backgroundColor = "white";
id.style.color = "black";
id.setAttribute("contentEditable", "true");
}
Upvotes: 1