jal jal - 3 months ago 29
Ajax Question

Sending parts of form using jQuery serialize() and AJAX

I'm trying to send parts of one form by AJAX using jQuery's serialize. The form has 16 textfields. I have 4 buttons. The

button0
sends the textfields 0,1,2,3, and
button1
sends the textfields 4,5,6,7, etc etc. How can I do it?

HTML

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Serialize</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<form id='miForm' class='miForm' name='miForm' action='env.php' method='POST'>

</form>
</body>
</html>


jQuery:

$(document).ready(function(){
for(i=0;i<16;i++){
$('form').append('Campo de texto '+i+'<input type="text" id="txt'+i+'" value="Campo '+i+'" readonly="yes"/><br>');
}
for(i=0;i<4;i++){
$('form').append('<input type="button" id="butEnv'+i+'" value="Enviar'+i+'"/><br>');
}
$('form').append('<input type="button" id="butGen" value="Enviar Global"/><br>');

});

Answer

If you really want to stay with only one form try something like I did in this fiddle.

Create sub parts for your form.

<form>
    <div id="first">
        <input name="tbox1" type="text">
        <input name="tbox2" type="text">
        <input name="tbox3" type="text">    
        <input id="button1" type="button" value="button1">  
    </div>
    <div id="second">
        <input name="tbox4" type="text">
        <input name="tbox5" type="text">
        <input name="tbox6" type="text">    
        <input id="button2" type="button" value="button2">  
    </div>
</form>

And then just select all the elements of the parts:

$(document).ready(function() {
    $('#button1').on('click', function() {
        alert($('#first input').serialize());
    });

      $('#button2').on('click', function() {
        alert($('#second input').serialize());
    });
});

Of course if you also have select boxes you have to add them to the selectors. For example:

$('#second input, #second select').serialize()
Comments