简体   繁体   中英

change form field value with javascript

<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.

You can handle it like so:

The HTML:

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

The 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

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

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

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

or let d be:

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

Not sure if you need document but I think you do.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM