gpt4 book ai didi

javascript - jQuery Serialize 与 Bootstrap 单选按钮组间歇性工作

转载 作者:行者123 更新时间:2023-11-27 23:55:34 25 4
gpt4 key购买 nike

我正在尝试在单击 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.

所有这些都准确地解释了为什么它会间歇性地工作。因为有时您碰巧 检查 单选按钮,所以它被认为是 “打开” 并且您的函数序列化该输入按钮。

这里有一个解决方法:

不使用单选按钮类型的输入,而是使用普通输入并将显示设置为无。

<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>

Bootply Demo

关于javascript - jQuery Serialize 与 Bootstrap 单选按钮组间歇性工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24167602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com