Tom Tom - 2 months ago 8
Ajax Question

Jquery - serialize form fields in DIV's by class?

Is it possible to get form field data and serialize it by using the class assigned to two divs ?

I have 4 divs that contain form fields, only two DIVs are shown at a time. What is shown depends on a drop down selection.


  • if
    select = 1
    , the divs with the class
    classOne
    are show and divs with
    classTwo
    are hidden

  • if
    select = 2
    , the divs with the class
    classTwo
    are show and divs with
    classOne
    are hidden



When I submit the form, I want to serialize either both divs with
classOne
, or
classTwo
, depending on what was selected in the dropdown.

So far I can't get it to serialize the form date from the divs..

data: $('.classOne').serializeArray(),


This doesn't pass any data to my back end script.

Answer

You need to target the form controls within those elements. You can use the pseudo selector :input to cover various control tags and types

data: $('.classOne :input').serializeArray()

DEMO

Another common way to do this is to use <fieldset> tags and disable the inactive ones. Disabling a fieldset disables any form controls within it so you can then effectively use serialize() on the whole form since it does not include disabled controls

Comments