Reputation: 13
I am trying to use parameters to put a variable into a .innerHTML. However, whenever I try to pass something in, it tends to give me an error because it's trying to find the innerHTML of a nonexistent item. I want the inner HTML to be customizable for several different functions.
function roll(type, num, type2){
var total = (Math.floor(Math.random()*type)+1)
var total2 = total * num;
type2.innerHTML = total2;
}
d20button.onclick = function(){
roll(19,1, 'd20p');
}
So the idea is that when I use different onclick buttons, I can pass in different variables depending on what the user enters. However, instead of using d20p.innerHTML, it keeps using type2.innerHTML. I'm wondering if there is a way to make it use d20p.innerHTML, while also leaving it open for other options.
Upvotes: 1
Views: 460
Reputation: 36564
'd20p'
is string which is passed as type2
in roll
. Strings donot have any property named innerHTML
so you should use document.getElementById()
before accessing innerHTML
function roll(type, num, type2){
var total = (Math.floor(Math.random()*type)+1)
var total2 = total * num;
document.getElementById(type2).innerHTML = total2;
}
If you want to change the innerHTML
of any button clicked then you can pass this
as parameter from onclick
event which will refer to the button clicked.
d20button.onclick = function(){
roll(19,1,this);
}
function roll(type, num, type2){
var total = (Math.floor(Math.random()*type)+1)
var total2 = total * num;
type2.innerHTML = total2;
}
Upvotes: 1