Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip hidden inputs in Jquery serialize

Tags:

jquery

I have forms with inputs of hidden and visible like below.In this example I want to serialize only name='country' which is not hidden

<form id="finalform">
<input type='hidden' name='sid' value='901271316' />
<input type='hidden' name='tco_currency' value='USD'>
<input   name='country' value='India' />
</form>

I tried below code but its serializing even hidden inputs.

var frm = $("form#finalform:visible");
 var add= JSON.stringify(frm.serializeArray());
like image 964
Vishnu Avatar asked Apr 10 '15 16:04

Vishnu


3 Answers

use below code . not(:hidden) will not include input type hidden in serialize()

check DEMO

var frm  = $('#finalform').find(":input:not(:hidden)").serialize();

Or

var frm  = $('#finalform :input:not(:hidden)').serialize();

DEMO

var frm  = $('#finalform :input:not(:hidden)').serializeArray();

var frm1  = $('#finalform').find(":input:not(:hidden)").serializeArray();

$('#firstOutput').text(JSON.stringify(frm))
$('#secondOutput').text(JSON.stringify(frm1))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="finalform">
 <input type='hidden' name='sid' value='901271316' />
 <input type='hidden' name='tco_currency' value='USD'>
 <input   name='country' value='India' />
</form>


<div id="firstOutput"> </div>
<div id="secondOutput"> </div>
like image 64
Nishit Maheta Avatar answered Oct 12 '22 23:10

Nishit Maheta


I find this a cleaner way of doing it:

var frm = $('#finalform [type!="hidden"]').serialize()
like image 37
nbz Avatar answered Oct 13 '22 00:10

nbz


You can make a temporary copy of it and remove the hidden inputs from it before serializing :

var form = $("#finalform").clone();
$(form).find("input[type=hidden]").remove()
var serialized = $(form).serializeArray();
like image 33
Tristan Foureur Avatar answered Oct 12 '22 22:10

Tristan Foureur