<form>
// radio group 1
<input type="radio" name="a" value="Y">Yes
<input type="radio" class="ml_10" name="a" value="N">No
<input type="radio" class="ml_10" name="a" value="O">Don't know</br>
// radio group 2
<input type="radio" name="b" value="Y">Yes
<input type="radio" class="ml_10" name="b" value="N">No
<input type="radio" class="ml_10" name="b" value="O">Don't know</br>
// text input
<input type='text' value='something' name="txt" />
</form>我有这个表格,我试图得到a作为false的值,如果在第一无线电组中没有选择的话。(其他无线电组也一样)它们可以是任意数量的无线电组。
var str = $('form input:not([type="radio"])').serialize();
var str1 = $("form input[type='radio']").map(function () {
return this.name + "=" + this.checked;
}).get().join("&");
if (str1 != "" && str != "") str += "&" + str1;
else str += str1;输出是:txt=something&a=false&a=false&a=false&b=false&b=false&b=false
正如你所看到的,我对一组中的每台收音机都是错误的。但是,如果没有选择,我只想要a=false。我怎样才能做到这一点?
Fiddle : http://jsfiddle.net/WcxwV/
编辑:
预期产出:
txt=something&a=false&b=false
发布于 2013-05-16 22:42:46
我只需执行var str = $('form').serialize();,然后将缺少的变量视为未选中。这就是预期的用途。我看不出有什么理由手动将其设置为false。
发布于 2015-08-21 20:19:51
如果您刚刚添加了另一个被选中的隐藏单选按钮及其value="",您的问题将得到解决。
<input type="radio" name="a" value="" checked style="display:none;">发布于 2016-08-03 03:37:22
尝尝这个
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
var $radio = $('input[type=radio],input[type=checkbox]',this);
$.each($radio,function(){
if(!o.hasOwnProperty(this.name)){
o[this.name] = '';
}
});
return o;
};https://stackoverflow.com/questions/16598539
复制相似问题