Because it was a response to the attacks of 9/11. The Taliban refused to turn over Al Qaeda leadership. The terrorist attacks were planned from bases within Afghanistan. Any nation that is attacked has a right to defend itself and the U.S. decision to invade had enormous support.
The better question is what were we doing there for 20 years. Either treat the offensive as a "mission accomplished" or treat it as a strategic base from which to hold onto influence and power in the middle-east. But, what we have is a half-assed attempt to install "western democracy" in a country that never wanted it and as a result we have gifted the Taliban with some new hardware and military surplus as the Afghan forces literally handed over their guns.