Refactored onkeyp function