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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2338144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:16:54  来源:igfitidea点击:

How can I set the Name attribute of an input field using Jquery?

jqueryformsattributes

提问by TikaL13

Quick question... I was wondering how I can get this to happen.

快速提问...我想知道如何才能做到这一点。

Okay I have an input field like such:

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

<input type="text" id="input1" size="10" name="" value="" class="checked other_amount" onfocus="Toggle('radio1', 'input1');" />

I would like to click on a div with an ID of #resetPrompt and fill the empty name attr from the input with "other_amount"

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

I'm out of ideas its been a long day

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

Thanks guys,

谢谢你们,

Matt

马特

回答by Alex Weber

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

回答by eugene

This is for all the googlers out there:

这适用于所有谷歌员工:

It should be noted that Alex's proposal, though functional in most "real" browsers, does not work in ie 8 and below (jquery 1.6.2). When setting the "name" attribute of an input field, Microsoft, to address a bug, added a fictitious "submitName" attribute when dynamic input fields are attached to the DOM.

应该注意的是,Alex 的提议虽然在大多数“真实”浏览器中都有效,但在 ie 8 及以下版本(jquery 1.6.2)中不起作用。在设置输入字段的“名称”属性时,为了解决错误,当动态输入字段附加到 DOM 时,Microsoft 添加了一个虚构的“提交名称”属性。

To workaround the problem in ie, either force your users to upgrade, use Firefox, Chrome, etc. or you'll need to add the input field manually:

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

$("#resetPrompt").click(function(){
   $("#input1").remove();
   $("#input_container").append('<input id="input1" name="' + other_amount + "' type="text" class="checked other_amount" onFocus="Toggle(\'radio1\', \'input1\');" />');
});

回答by Raul Agrait

If "other_amount" is the ID of the other input, use attrand valas follows:

如果“other_amount”是其他输入的 ID,则使用attrval如下:

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

回答by tvanfosson

Assuming that "other_amount" is the name, not id of the corresponding input.

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

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