[英]How to change multiple input values with javascript loop
I have a case where I'd like to be able to allow the users to change their units system. 我有一种情况,希望能够允许用户更改其单位制。 In doing so I would have to go through the entire page and:
为此,我必须遍历整个页面并:
a) change the units description from text and a)从文本更改单位描述,并
b) convert the current values to the new units. b)将当前值转换为新单位。
The first part I can achieve ok using getElementById
and innerHTML
. 我可以使用
getElementById
和innerHTML
来完成第一部分。 Its the second part I am having difficulty with 这是我遇到的第二部分
Example - I have two entries with units of "GIIP (BCF):" and values of 235 and 100 respectively; 示例-我有两个条目,单位为“ GIIP(BCF):”,值分别为235和100。
<table id="table2">
<tr><input id="calc" type="button" value="Test Convert" onClick="conversion();" />
<td class="leftcol" id=test_units1>GIIP (BCF):</td>
<td><input id=test_value1 size="7" type="number" value="235"> </td>
<td class="leftcol" id=test_units2>GIIP (BCF):</td>
<td><input id=test_value2 size="7" type="number" value="100" > </td></table>
When I click the button, the following executes (where for the example I want to change the units description and simply double the existing value); 当我单击按钮时,将执行以下操作(在本例中,我想更改单位描述,只需将现有值加倍);
function conversion() {
for (var i = 1, e; e = document.getElementById("test_units" + i); ++i)
e.innerHTML = "m<sup>3</sup>";
convert_values();
}
function convert_values() {
for (var i = 1, e; e = parseFloat(document.getValueById("test_value" + i)); ++i)
var val = (e*2).toString();
e.innerHTML = val;
}
The units description converts OK, but the values are unaffected. 单位描述将转换为OK,但值不受影响。 Can anyone suggest a method to convert the values in a more elegant fashion (or indeed at all!).
任何人都可以提出一种以更优雅的方式(或者说根本!)转换值的方法。 Bear in mind that I'll have many of these conversions to do on any one page/form.
请记住,我将在任何一页/表格上进行许多此类转换。
To retrieve the value of an input object, you use element.value
where element
is a reference to the input tag. 要检索输入对象的值,请使用
element.value
,其中element
是对输入标签的引用。 To set the value of an input, you use element.value = newValue;
要设置输入值,请使用
element.value = newValue;
. 。 You don't use
.innerHTML
for either. 您都不使用
.innerHTML
。 Also, in your code, you are treating e
as the value in one place and the element in another place. 同样,在您的代码中,您将
e
放在一个位置作为值,将元素放在另一个位置。
So, you can do it like this: 因此,您可以这样做:
function convert_values() {
for (var i = 1; i < 2; i++)
var obj = document.getElementById("test_value" + i);
obj.value = Number(obj.value) * 2;
}
This should do it: 应该这样做:
function convert_values() {
for (var i = 1, e; e = document.getElementById("test_value" + i); ++i)
e.value = parseFloat(e.value)*2;
}
Works like what you had, except uses getElementById
and e.value
, you had something funny going on in your version... 像您一样工作,除了使用
getElementById
和e.value
,您的版本中发生了一些有趣的事情……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.