更改输入名称值
是否可以更改输入元素的名称值?
这是我的代码,但我可以设置除名称之外的任何内容。
$('#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();
}
});
有什么想法为什么设置名称属性不起作用?
希望大家多多指教
Is it possible to change the name value of an input element?
Here is my code but i can set anything but the name.
$('#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();
}
});
Any ideas why setting a name attr does not work ?
Hope you can advise
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在这里瞎猜,看来你想阻止这些元素提交到服务器,如果是这种情况,而不是尝试更改
name
属性,你可以设置禁用
属性,像这样:当表单元素具有
disabled
属性时,它不能 成功,表示提交到服务器时不会被收录。因此,在上面的示例中,只需从一开始就给出两个输入name="user[state]"
,这将从您的POST(或 GET)中排除您不想要的输入>
它没有直接回答问题,我意识到这一点,但这是另一种(我认为)更简单的方法来避免问题:)您可以使用
.toggle(bool)
但我认为它破坏了示例,所以我在上面将其未压缩,简短版本如下所示:I'm taking a shot in the dark here, it seems like you want to prevent these elements from submitting to the server, if that's the case instead of trying to change the
name
attribute, you can set thedisabled
attribute, like this:When a form element has the
disabled
attribute, it can't be successful, which means it won't be included when you submit it to the server. So in the above example just give both inputsname="user[state]"
from the start, and this will exclude the one you don't want from the POST (or GET) that your<form>
does.It doesn't answer the question directly, I realize this, but it's another (I think) simpler way to avoid the problem :) You can shorten this down further by using
.toggle(bool)
but I think it destroys the example, so I left it uncompressed above, the short version would look like this:如果我没记错的话,这是一个 IE bug。我必须将 JQuery obj 转换为字符串,将名称更改为字符串,然后在 html 字符串周围创建一个新的 jquery 对象。
所以
显然更改名称属性比应有的更困难:/
If I remember correctly, this is an IE bug. I had to convert the JQuery obj to a string, do the name changing as a string and then create a new jquery object around the html string.
so
Apparently changing the name attribute is more difficult than it should be :/