0

I wrote this script in order to generate a random first name from an array of names, and insert it into a specific div class ('text'):

var Firstname = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ]
var fnoutput = Firstname[Math.random()*Firstname.length | 0]
window.onload = function firstName(){
  fnoutput = Firstname[Math.random()*Firstname.length | 0]
  document.getElementsByClassName('text')[0].innerHTML = fnoutput
}
<div class="text"></div>
<div class="text2"></div>

Now i want to make a identical function, which generates a surname as well, from it's own seperate array of surnames, and insert it into another div class ('text2')

I tried copy/pasting the working script, and changes the values of the array and targeted it towards 'text2':

var Firstname = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ]
var fnoutput = Firstname[Math.random()*Firstname.length | 0]
window.onload = function firstName(){
  fnoutput = Firstname[Math.random()*Firstname.length | 0]
  document.getElementsByClassName('text')[0].innerHTML = fnoutput
}

var Surname = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', ]
var snoutput = Surname[Math.random()*Surname.length | 0]
window.onload = function surName(){
  snoutput = Surname[Math.random()*Surname.length | 0]
  document.getElementsByClassName('text2')[0].innerHTML = snoutput
}
<div class="text"></div>
<div class="text2"></div>

As you see, it now ignores the first script, and only outputs a value from the second.

How do i make three of these scripts work nicely along each other (i plan to add a middle name as well)?

Thanks!

emiliano85
  • 129
  • 10

1 Answers1

2

i modified your code a bit, hope this what you want. Good luck

var Firstname = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ]
var Surname = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', ]
var fnoutput = Firstname[Math.random()*Firstname.length | 0]
var snoutput = Surname[Math.random()*Surname.length | 0]
window.onload = function firstName(){
  fnoutput = Firstname[Math.random()*Firstname.length | 0]
  document.getElementsByClassName('text')[0].innerHTML = fnoutput
  snoutput = Surname[Math.random()*Surname.length | 0]
  document.getElementsByClassName('text2')[0].innerHTML = snoutput
}
<div class="text"></div>
<div class="text2"></div>