Refactored JS code for the form