2009年10月15日 星期四

How do I use jQuery’s form.serialize but exclude empty fields

You could do it with a regex...

var orig = $('#myForm').serialize();
var withoutEmpties = orig.replace(/[^&]+=\.?(?:&|$)/g, '')
Test cases:

orig = "a=&b=.&c=&d=.&e=";
new => ""

orig = "a=&b=bbb&c=.&d=ddd&e=";
new => "b=bbb&d=ddd&" // dunno if that trailing & is a problem or not

.replace(/[^&]+=\.?(&|$)/g, '') covers both cases. But I'd add .replace(/&$/, '') to remove the trailing &

沒有留言:

wibiya widget