...

View Full Version : getAttribute help



ninnypants
07-31-2008, 01:22 AM
I have this function that I'm using on elements to add there name into a form element, but I don't want to write it out on every element but when I use it in a function it throws an error saying that "this.getAttribute()" is not a function.
Here is my function.


function updateForm(el_id){
document.getElementById(el_id).value = this.getAttribute('name');
}

Mikebert4
07-31-2008, 09:35 AM
thats because we don't access attributes through a method such as getAttribute().

we access the attributes through the method '.attribute'
if you want to get the name of an element:



this.name

...or...

document.getElementById("an_id").name


with that in mind your code becomes:



function updateForm(el_id,curr_id)
{
document.getElementById(el_id).value = curr_id.name;
}


and you would call the function thus:




onClick="UpdateForm(an_id, this);"

or onblur, onfocus, on mouseover, mouseout, etc etc..

rangana
07-31-2008, 09:50 AM
Mike, I have to disagree.

We can access the element's name via getAttribute().

The problem at ninnypant's end is that he uses the this keyword which was referencing to the updateForm function and not the element where the onclick was called (I suppose).

The fix is by adding an additional parameter on updateForm function. Highlighted should be added and the one in red should be replaced with e:


function updateForm(el_id,e){
document.getElementById(el_id).value = this.getAttribute('name');
}


Together with this ammendment is to send the this keyword to our function. Add highlighted on each function call:


updateForm('elementID','this')


Hope it makes sense.

ninnypants
07-31-2008, 03:39 PM
Mike, I have to disagree.

We can access the element's name via getAttribute().

The problem at ninnypant's end is that he uses the this keyword which was referencing to the updateForm function and not the element where the onclick was called (I suppose).

The fix is by adding an additional parameter on updateForm function. Highlighted should be added and the one in red should be replaced with e:


function updateForm(el_id,e){
document.getElementById(el_id).value = this.getAttribute('name');
}


Together with this ammendment is to send the this keyword to our function. Add highlighted on each function call:


updateForm('elementID','this')


Hope it makes sense.

It didn't work at first but now it's working thanks.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum