我尝试在单击 Bootstrap .btn
标签时序列化单选按钮。
HTML:
<div class="btn-group" data-toggle="buttons">
<label label-default="" class="btn btn-primary">
<input id="option1" name="options" type="radio" value="1">Option 1</label>
<label label-default="" class="btn btn-primary active">
<input id="option2" name="options" type="radio" value="1">Option 2</label>
<label label-default="" class="btn btn-primary">
<input id="option3" name="options" type="radio" value="1">Option 3</label>
</div>
jQuery:
$(".btn").on('click', function(){
console.log("Name: " + $(this).children('input').attr('name') );
console.log("Value: " + $(this).children('input').val() );
console.log("Serialized: " + $(this).children('input').serialize() );
})
名称和值始终出现在我的输出中,但序列化间歇性地工作(有时返回序列化值,有时返回空字符串),我不明白为什么。
此处演示:http://www.bootply.com/86422#
谢谢!
最佳答案
如果您遇到问题,您确实应该阅读有关 jQuery 的 .serialize()
函数的所有文档。
来自.serialize() API :
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
现在来自 W3 的文档 successful controls :
For radio buttons that share the same value of the name attribute, only the "on" radio button may be successful.
所有这些都准确地解释了它间歇性工作的原因。因为有时您碰巧检查
单选按钮,因此它被视为“on”
并且您的函数会序列化该输入按钮。
这是一个解决方法:
不要使用单选按钮类型的输入,只需使用普通输入并将显示设置为无。
<div id="mode-group" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input name="mode" id="option1" value="cash/check" style="display: none">Cash / Cheque / Bank Transfer</label>
<label class="btn btn-primary">
<input name="mode" id="option2" value="jobsBuddy" style="display: none">JobsBuddy Disbursement</label>
</div>
关于javascript - jQuery Serialize 与 Bootstrap 单选按钮组间歇性工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24167602/