NASA had already proposed the idea to Kennedy, according to this NASA history article (citing a memo titled, “National Aeronautics and Space Administration Budget Problem,” dated 22 March 1961):
Firm evidence for Kennedy's essential unwillingness to commit to an aggressive space program came in March 1961 when the NASA Administrator, James E. Webb, submitted a request that greatly expanded his agency's fiscal year 1962 budget so as to permit a Moon landing before the end of the decade. While the Apollo lunar landing program had existed as a longterm goal of NASA during the Eisenhower administration, Webb proposed greatly expanding and accelerating it. Kennedy's budget director, David E. Bell, objected to this large increase and debated Webb on the merits of an accelerated lunar landing program. In the end the president was unwilling to obligate the nation to a much bigger and more costly space program. Instead, in good political fashion, he approved a modest increase in the NASA budget to allow for development of the big launch vehicles that would eventually be required to support a Moon landing.
The article goes on to suggest two reasons that Kennedy came to support the lunar program: humiliation over Gagarin's being the first person in orbit, and (closer to home) humiliation over the Bay of Pigs invasion.