Out of universe, they were attached using velcro or pins, or sometimes magnetically in scenes where they were donned or doffed. Here is a discussion of the issue:
It's never stated in 'canon' how it is done, but for costuming, they are attached with velcro as shown through the It's A Wrap! sale and auction. :)
I even once read that they had two versions, one velcro-attached and another attached with a strong magnet - you can see the latter in the DS9 episode where Dax meets his/her former love and Sisko brings her upside down badge into the right position on the dress uniform again. They used the velcro version most of the time when the combadge didn't have to be removed for script reasons.
Following the link to the sale and auction, and then a few more links beyond that, I found item descriptions for several of the combadges sold there:
- one with "a Velcro patch on the back"
- one, two, three with "an adhered Velcro placement for a corresponding one affixed to almost any uniform"
- one with "no Velcro placement" but "pin backing for bending over into fabric"
- one "with Velcro backing"
- one with "the reverse [...] hollowed out to allow a cavity for a Velcro placement"
- one with "a Velcro placement on the reverse"
- one with " four pins that have lost a degree of their fastening quality, a three pin placement and a single pin placement that push through the collar of the undershirt"
- one with "a Velcro placement"
These props span many different seasons of Star Trek.
Here is a more detailed but also more speculative answer, in which pins, velcro, and various ways of using magnets are discussed. It makes for an interesting read, but the above quotes seem to be more definite. The top post here also says the answer is magnets and velcro.
In-universe, they are attached **magnetically**. From [Star Trek Answers Wikia](http://star-trek.answers.wikia.com/wiki/How_are_combadges_and_rank_pips_attached_to_the_uniform):
They are done magnetically. The fabric has metallic properties that they where [sic]. Even though the uniforms are not actually metallic. They "resemble" it as far as teh [sic] physics of the com badges are concerned.
In the Star Fleet Technical Manual (1973), it was referred to as "magnatomic adhesion"
And in the DS9 episode where Worf appeared, a metal strip on the side of the collar is seen (on the inside of where the pips go on the outside). Presumably something similar for the combadges? Although I have no clue how they seem to be able to stick onto any clothing. Probably best not to think about it (after all, it's just velcro in real life)