Search code examples
javascriptjqueryformsselectorsubform

jquery how to select form elements in sub-form div


say I have the following form:

​<form id="f">
    <input name="a"/>
    <input name="b"/>
    <div id="sub_part">
        <input name="c"/>
        <input name="d"/>
    </div>
</form>
<form id="e">
    <input name="a"/>
    <input name="b"/>
    <div id="sub_part2">
        <input name="c"/>
        <input name="d"/>
    </div>
</form>

I usually can get all the name->value pairs using .serialize(). For example. I know i can get the information from form f by using:

$('form#f').serialize();

What if just want the name->value pairs from the sub_part div in form f? What would the jquery selector be in this case? For this exercise I do not want to change the structure of the html.

Please check out this fiddle where I have the problem outlined: http://jsfiddle.net/gu9XB/4/

Notice way I am trying to select the sub form is not working.


Solution

  • Use this :

    $('#but1').click(function() {
        var data = $('form#f').serialize();
        alert(data);
    });
    
    $('#but2').click(function() {
        var data = $('#f #sub_part *').serialize();
        alert(data);
    });​
    

    Here is the DEMO