javascript 使用javascript更改表单字段值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3834018/
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-10-25 02:24:27  来源:igfitidea点击:

change form field value with javascript

javascript

提问by mohit

<script type="text/javascript">
function up(d,mul)
{
alert(d);
form1.d.value=mul;
}

</script>

up is a function name with which i am trying to update the value of field(field name=d). But its not working. plz somebody help me.

up 是一个函数名,我试图用它来更新字段(字段名=d)的值。但它不工作。请有人帮助我。

回答by Kristoffer Sall-Storgaard

You can handle it like so:

你可以这样处理:

The HTML:

HTML:

?<form method='post' action='doesnt_matter'>
<input type='text' name='field1' />
<input type='text' name='field2' />
</form>??????????????????????????????????????????????????????????????????

The JavaScript:

JavaScript:

form = document.forms[0];
function up(d,mul)
{
    alert(d);
    form[d].value=mul;
}



up('field1','Hello field 1');
up('field2','Hello field 2');
?

Working jsfiddle

工作 jsfiddle

回答by Felix Kling

Well you pass das parameter. So you either have to do (renaming it do fieldname):

那么你d作为参数传递。所以你要么必须做(重命名它做fieldname):

function up(fieldname,mul)
{
    document.form1[fieldname].value=mul;
}

and calling it with up('d', 'newValue'),

并调用它 up('d', 'newValue')

or let dbe:

或者让我们d

function up(mul)
{
    document.form1.d.value=mul;
} 

Not sure if you need documentbut I think you do.

不确定您是否需要,document但我认为您需要。

See an example here: http://jsfiddle.net/8uyv8/

在此处查看示例:http: //jsfiddle.net/8uyv8/

回答by methodin

function up(d,mul) { alert(d); form1[d].value=mul; }

You can't use d literally here as it assumes you are looking for an element named "d". So you have to use d in a context where it will use it's value, in this case, an array index.

您不能在这里直接使用 d,因为它假定您正在寻找名为“d”的元素。所以你必须在一个上下文中使用 d ,它将使用它的值,在这种情况下,是一个数组索引。