如何使用Jquery设置输入字段的Name属性?

快速问题……我想知道如何才能实现这一目标。

好的,我有一个像这样的输入字段:

 

我想点击ID为#resetPrompt的div,并使用“other_amount”从输入中填充空名称attr

我没有想法,这是漫长的一天

多谢你们,

马特

 $('#resetPrompt').click(function(){ $('#input1').attr('name', 'other_amount'); }); 

这适用于所有的googlers:

应该注意的是,Alex的提议虽然在大多数“真实”浏览器中起作用,但在8及以下(jquery 1.6.2)中不起作用。 当设置输入字段的“name”属性时,为了解决bug,在动态输入字段附加到DOM时添加了虚构的“submitName”属性。

要解决问题,或者强制用户升级,使用Firefox,Chrome等,或者您需要手动添加输入字段:

 $("#resetPrompt").click(function(){ $("#input1").remove(); $("#input_container").append(''); }); 

假设“other_amount”是名称,而不是相应输入的id。

 $('#resetPrompt').click( function() { $('#input1').attr('name', $('[name=other_amount]').val()); }); 

如果“other_amount”是另一个输入的ID,请使用attr和val ,如下所示:

 $("#resetPrompt").click(function(){ var otherValue = $("#other_amount").val(); $("#input1").attr("name", "someName"); }