Refactored js function to control number selection