A hydrogel consists of a cross-linked polymer network and solvent molecules. Depending on its chemical and mechanical environment, the polymer network may undergo enormous volume change. The present work develops a general formulation based on a variational approach, which leads to a set of governing equations coupling mechanical and chemical equilibrium conditions along with proper boundary conditions. A specific material model is employed in a finite element implementation, for which the nonlinear constitutive behavior is derived from a free energy function, with explicit formula for the true stress and tangent modulus at the current state of deformation and chemical potential. Such implementation enables numerical simulations of hydrogels swelling under various constraints. Several examples are presented, with both homogeneous and inhomogeneous swelling deformation. In particular, the effect of geometric constraint is emphasized for inhomogeneous swelling of surface-attached hydrogel lines of rectangular cross-sections, which depends on the width-to-height aspect ratio of the line. The present numerical simulations show that, beyond a critical aspect ratio, crease-like surface instability occurs upon swelling.