gpt4 book ai didi

jquery - 如何使用 jQuery 获取单选按钮的值?

转载 作者:行者123 更新时间:2023-12-01 07:04:08 26 4
gpt4 key购买 nike

我当前的代码从表单获取所有数据,然后将其作为数组输出到控制台(我正在测试联系表单)。它返回的所有数据都是正确的,但单选按钮的值始终相同。

html:

<form class="form1" action="form.php" method="post">
<div class="form-sect">
<div class="formb-check">
<input type="text" name="name" placeholder="Name" class="formb-small">
<input type="text" name="id" placeholder="ID: 00000000" class="formb-small">
</div>
</div>
<div class="form-sect">
<div class="formb-srv">
<div class="formb-check">
<input type="radio" name="server" id="server-1" value="Srv 1"><label for="server-1">Server 1</label>
<input type="radio" name="server" id="server-2" value="Srv 2"><label for="server-2">Server 2</label>
</div>
</div>
</div>
<div>
<div>
<textarea name="message" placeholder="Message....."></textarea>
<button type="submit" name="submit">Submit Report</button>
</div>
</div>

jQuery:

$('form.form1').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};

that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();

data[name] = value;
});

$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});

return false; });

PHP:

<?php 
if(isset($_POST['name'], $_POST['id'], $_POST['server'], $_POST['message'])){
print_r($_POST);
} ?>

在我用于测试单选按钮的值的数组中,它始终是使用的第二个值,在此代码中它是 Srv 2。如下所示:[服务器] => Srv 2

最佳答案

您应该像这样序列化表单:

$('form.form1').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
});

关于jquery - 如何使用 jQuery 获取单选按钮的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176685/

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