开发者

javascript table like form manipulation

开发者 https://www.devze.com 2022-12-08 16:20 出处:网络
Basically I\'ve got a form in a table. Each row of the table has some input fields. For example: col1col2

Basically I've got a form in a table. Each row of the table has some input fields.

For example:

     col1  col2 
row1  A     C
row2  B     D

Some of the input fields depend on others. When I type something in A, B and C, D is locked, and its value is automatically filled by the calculation of A, B and C.

Also, the user can enter values into the fields in any order, and the one left is calculated.

D开发者_高级运维oes anyone know if there's a jQuery/prototype plugin can do something like this?


There are a couple simple things you can do, and they don't require jQuery. First, to "lock" (disable) field D, you can add disabled = "disabled" to the HTML input tag like so:

<input type="text" id="D" disabled="disabled" />

This will make the text box readable, but not editable. I'm assuming that was what you were attempting to accomplish.

Second, concerning the automatic calculation of the contents of A, B, and C, you can add event handlers to the input tags so that when an event happens (such as pressing a keyboard key or moving focus to a different element), you can execute a function.

To do this, first declare a Javascript function in your document like so:

<script language="javascript">

function calculate() {
  document.getElementById('D').value = parseInt(document.getElementById('A')) + parseInt(document.getElementById('B')) + parseInt(document.getElementById('C'));
}

</script>

(This overly-simplistic function assumes all the inputs have ids of 'A', 'B', 'C', and 'D' respectively. Note that this also assumes you are only trying to calculate integers, and this function does not even attempt to do a sanity check on the user input to make sure the text fields have the expected values. Also note that this function is untested.)

Once you have the function, you can add it to each of the text fields using Javascript event handlers. For example, if you want the calculation to occur when the user clicks on something outside the input box, add onblur="calculate()" to the input tag like so:

<input type="text" id="A" onblur="javascript:calculate()" />

You can choose the appropriate event handler that you want. For more on event handlers, click here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号