How to make a serialize of certain part of the form?

Asked

Viewed 234 times

1

I own a Togglable tabs and would like to serialize the data only of the current index or active tab.

This form is "global" so to speak, and this tabs gets inside, an example of this would be:

<form>
  <div class="servicos">
    <label>foo</label>
    <input type="text" name="foo">
    <label>foo</label>
    <input type="text" name="bar">
  </div>
  <div class="configuracoes">
    <label>foo2</label>
    <input type="text" name="foo2">
    <label>foo2</label>
    <input type="text" name="bar2">
  </div>
  <button id="enviar">Enviar</button>
</form>

Let’s say I’m on the "settings" tab when saving I’d just grab foo2,bar2.

I’ve tried it this way:

$("form").submit(function(e) {
  e.preventDefault();
  $(this).find('.configuracoes').serialize();
});

The return of serialize is empty, ?

  • $(this).find('.active').serialize(); When the tab is visible, the . active class is added to the element. So with that code he’ll only take the values of whatever’s inside the element that’s visible.

  • @Gilsones this is exactly how I tested it, if you look at my example.

  • Try it like this then: $(this).find('.active [name]').serialize(); So he’ll take all the elements that have the attribute name (fields, texarea, select, radio, checkbox...) and will serialize

1 answer

1


I tested it here and it worked, with the same idea I mentioned.

$(function(){

  $("#enviar").on("click", function( e ) {
      e.preventDefault();
  
      alert( $("#formulario").find(".active [name]").serialize() );
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<form id="formulario">

<div class="container">
    <ul class="nav nav-tabs">
        <li class="nav active"><a href="#servicos" data-toggle="tab">Serviços</a></li>
        <li class="nav"><a href="#configuracoes" data-toggle="tab">Configurações</a></li>
    </ul>

    <!-- Tab panes -->
    <div class="tab-content">
        <div class="tab-pane fade in active servicos" id="servicos">
            <br>
            <label>foo</label>
            <input type="text" name="foo">
            <label>foo</label>
            <input type="text" name="bar">
        </div>
        <div class="tab-pane fade configuracoes" id="configuracoes">
            <br>
            <label>foo2</label>
            <input type="text" name="foo2">
            <label>foo2</label>
            <input type="text" name="bar2">
        </div>
    </div>
</div>

<br>
<input type="submit" value="Enviar" id="enviar">
  
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.