Change the javascript from 'undefined' at the end to a loop