Is there any difference between these solutions?
Solution 1:
// HTML:
<input id="theId" value="test" onclick="doSomething(this.id, this.value)"/>
// JavaScript:
function doSomething (id, value) {
// ...
}
...and Solution 2:
// HTML:
<input id="theId" value="test" onclick="doSomething(this.id)" />
// JavaScript:
function doSomething(id){
var value = document.getElementById(id).value;
// ...
}
Pass the object:
You can get all data from object:
Or pass the
id
only:Get the object and after that value:
The second function should have:
Then they are basically the same function.
Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.
This should also work.
In the second version, you're passing the String returned from
this.id
. Not the element itself.So
id.value
won't give you what you want.You would need to pass the element with
this
.then:
Note: In some browsers, the second one would work if you did:
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with
this
instead of fetching it again with its ID.