StackExchange does something more complicated than you probably need. Their preview functionality is contained in the javascript scripts that they source (creating a StackExchange object). They do all sorts of nice clever things --- and if you want to understand it fully, you can read the javascript source.
But I think you would probably be fine with using something like this --- which I found after a quick search engine and choosing the top hit. The code there is pretty straightforward and copy-able.
Aside: I tried to decide if I thought this was on-topic here. I would say it's borderline on-topic, but probably on the off-topic side of the border. If you have further programming questions, the appropriate place to ask them is on one of the programming sites on the network, such as StackOverflow.