gpt4 book ai didi

jQuery 序列化隐藏(显示 :none) form elemens does not work. 解决方法?

转载 作者:行者123 更新时间:2023-12-01 01:03:41 25 4
gpt4 key购买 nike

我有以下问题:

我有一个需要序列化的表单,但我正在使用 javascript 来更改选择字段的外观。这意味着,使用 display:none 隐藏真正的选择字段。我现在的问题是,jQuery 确实识别隐藏的选择,但只序列化第一个值,而不序列化选定的值。

<select name="publish"><br/>
<option value="1">yes</option><br/>
<option value="2" selected="selected">no</option><br/>
</select>

jQuery.serialzie: publish=1

所以它给了我第一个而不是正确的值。

有什么解决方法吗?

解决方案
好的,正如 RobW 所提到的,最好的解决方案可能是让 JavaScript 通过设置 selectElement.selectedIndex = 5 来选择您想要的选项。

但是我的解决方案有点不同,因为由于维护问题,我不想更改用于更改我选择的外观的插件(例如,每次发布新版本时都需要更改脚本) 。我只是使用自定义函数进行序列化。

(function($) {
$.fn.serializer = function() {
var toReturn = [];
var elements = $(this).find(':input').get();
$.each(elements, function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type)))
{
var val = $(this).val();
// if is select, check selected
if(this.nodeName == "SELECT")
{
val = $(this).find('option:selected').val();
}
toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
}
});
return toReturn.join("&").replace(/%20/g, "+");
}
})(jQuery);

最佳答案

如果问题是由隐藏元素引起的,请在序列化之前暂时显示它们:

var $form = $('#myForm');
var hidden = $form.find(':hidden'); // Select all hidden elements
hidden.show(); // Show them
var string = $form.serialize(); // Serialize form
hidden.hide(); // Hide them again

编辑:您似乎正在尝试通过设置 selected=selected 属性来选择一个选项。您应该使用 selectedIndex 更改所选选项:

var select = $("#myselect")[0]; //DOM element
select.selectedIndex = 5; //Example, select 6th option

关于jQuery 序列化隐藏(显示 :none) form elemens does not work. 解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8023771/

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