How to write a value from textfield 1 to textfield 2 and vice versa

问题: I wrote a little function in JS which will take a numerical input from textfield 1 and calculate an aspect ratio of 2/3 of it and write this value to textfield 2. Now I wan...

问题:

I wrote a little function in JS which will take a numerical input from textfield 1 and calculate an aspect ratio of 2/3 of it and write this value to textfield 2. Now I want the same functionality for textfield 2 but with a ratio of 3/2, so wherever the user inputs a value I want the other textfiled to be automatically filled with the calculated value.

Here is my code which works for inputting into textfiles 1 and showing 2/3 of that in textfiles 2:

function change()
            {    
            var ex1Val = (document.getElementById("ex1")).value;

            if (ex1Val < "0" || "9" < ex1Val)
                {
                //(document.getElementById("ex1")).value = "";
                (document.getElementById("ex1")).focus();
                return false;
                }
            else
                {
                (document.getElementById("ex2")).value = ((ex1Val * 2) / 3);
                }
            };

I have tried to copy the function and edit the ids and aspect ratio, but that does not work.

If not JS, Jquery will be fine, too.


回答1:

You can use onInput="change(this.id)" event and check for id and calculate your aspect ratio.

function change(id) {
  var ex1Val = (document.getElementById(id)).value;
  if (id == "ext1") {
    (document.getElementById("ext2")).value = ((ex1Val * 2) / 3);
  } else if (id === "ext2") {
    (document.getElementById("ext1")).value = ((ex1Val * 3) / 2);
  }

};
<input id="ext1" onInput="change(this.id)" />
<input id="ext2" onInput="change(this.id)" />

  • 发表于 2018-12-27 07:50
  • 阅读 ( 229 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除