gpt4 book ai didi

javascript - "How do I use jQuery' s form.serialize 但排除空字段“不起作用(使用 php)

转载 作者:行者123 更新时间:2023-11-30 07:15:36 24 4
gpt4 key购买 nike

我想使用 How do I use jQuery's form.serialize but exclude empty fields但它不起作用。我使用了一个重定向到 php 脚本的最小示例:

<html><head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function(){
$("#myForm :input[value!='']").serialize();
alert('JavaScript done');
});
});
</script>
</head>


<body>
<form id="myForm" action="php.php" method="get">
<input id=id1 name=name1 type="text" /><br>
<input id=id2 name=name2 type="text" /><br>
<input id=id3 name=name3 type="text" /><br>
<input id=id4 name=name4 type="text" />
<input type="submit" value="submit form"/>
</form>
</body></html>

这是php脚本

<?php
print_r($_GET);
?>

如果我只在第一个文本框中写入“111”,我会从 php 获取:

Array ( [name1] => 111 [name2] => [name3] => [name4] => )

因此,所有字段都进入了获取参数。

你能帮帮我吗?

TIA

最佳答案

您不能为 value 使用属性选择器,因为它是一个不断变化的属性。

使用.filter()

$(document).ready(function () {
$('#myForm').submit(function () {
$(this).find(":input").filter(function () {
return $.trim(this.value).length > 0
}).serialize();
alert('JavaScript done');
});
});

演示:Fiddle

注意:表单提交时只序列化输入字段不会发生变化,只有ajax提交表单才能使用。

如果你想做一个正常的表单提交但想删除空字段然后使用 .remove()

$(document).ready(function () {
$('#myForm').submit(function () {
$(this).find(":input").filter(function () {
return $.trim(this.value).length == 0
}).remove();
alert('JavaScript done');
});
});

关于javascript - "How do I use jQuery' s form.serialize 但排除空字段“不起作用(使用 php),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20189079/

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