gpt4 book ai didi

jquery - 更改输入名称值

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

是否可以更改输入元素的名称值?

这是我的代码,但我可以设置除名称之外的任何内容。

$('#country').change(function(){
var $country = $(this);
var $state = $('#state');
var $county = $("#county");
if($country.val() != 226){
$state.attr('name', '');
$state.closest('p').hide();
$county.attr('name', 'user[state]');
$county.closest('p').show();
}else{
$state.attr('name', 'user[state]');
$state.closest('p').show();
$county.attr('name', '');
$county.closest('p').hide();

}
});

知道为什么设置名称属性不起作用吗?

希望大家多多指教

最佳答案

我在这里瞎猜,看来你想阻止这些元素提交到服务器,如果是这种情况,而不是尝试更改 name属性,您可以设置 disabled attribute ,像这样:

$('#country').change(function() {
var $country = $(this), $state = $('#state'), $county = $("#county");
if($country.val() != 226) {
$state.attr('disabled', true).closest('p').hide();
$county.attr('disabled', false).closest('p').show();
} else {
$state.attr('disabled', false).closest('p').show();
$county.attr('disabled', true).closest('p').hide();
}
});

当表单元素具有 disabled 时属性,它不能是 successful ,这意味着当您将其提交到服务器时不会包含它。因此,在上面的示例中,只需给出两个输入 name="user[state]"从一开始,这将从您的 <form> 的 POST(或 GET)中排除您不想要的内容。确实如此。

它没有直接回答问题,我意识到这一点,但这是另一种(我认为)更简单的方法来避免问题:)您可以使用 .toggle(bool) 进一步缩短它但我认为它破坏了示例,所以我在上面保留了未压缩的状态,简短的版本如下所示:

$('#country').change(function() {
var is226 = $(this).val() == 226;
$('#state').attr('disabled', !is226).closest('p').toggle(is226);
$("#county").attr('disabled', is226).closest('p').toggle(!is226);
});

关于jquery - 更改输入名称值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3419805/

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