简体   繁体   English

如何使用javascript获取具有更改事件的文本框的第一个值?

[英]How to get first value of textbox with change event using javascript?

I have textbox with value binded from database. 我有文本框,值与数据库绑定。 I have onkeyup event in the textbox. 我在文本框中有onkeyup事件。 I want to make calculation like old value plus new value. 我想像旧值加上新值一样进行计算。 Is there a function that can get textbox value after page load using javascript? 是否存在可以使用javascript在页面加载后获取文本框值的功能?

eg First value while page load is 5 when I change textbox to 3, then label value would be 8 when I change textbox again to 4, then label value would be 9. 例如,当我将文本框更改为3时,页面加载时的第一个值为5,那么当我再次将文本框更改为4时,则标签值为8,然后标签值为9。

You have to preserve the original value in a data attribute in addition to knowing the actual value . 除了知道实际value之外,还必须将原始值保留在data属性中。 For example: 例如:

<input id="my-text-box" type="text" data-original-value="5" value="5">

Then you can access the original value via jQuery: 然后,您可以通过jQuery访问原始值:

$('#my-text-box').data().originalValue;

or in plain JavaScript: 或使用纯JavaScript:

var element = document.getElementById('my-text-box');
var originalValue = element.getAttribute("data-original-value");

and the new value with jQuery: 以及jQuery的新价值:

$('#my-text-box').val();

or in plain JavaScript: 或使用纯JavaScript:

var element = document.getElementById('my-text-box');
var originalValue = element.value;

EDIT: for plain JavaScript answers. 编辑:纯JavaScript答案。

If you have a text input with an id of my-text-input , and a variable called originalValue : 如果您有一个idmy-text-input ,并且有一个名为originalValue的变量:

window.onload( function() {
 originalValue = document.getElementById('my-text-input').value 
});

You can use data attribute and set the default value in it. 您可以使用data属性并在其中设置默认值。 Then use onchange event listener and once the focus is removed from the input it will get the default value and the new value. 然后使用onchange事件侦听器,一旦焦点从输入中移除,它将获得默认值和新值。 Use parseInt to convert string to number before adding 在添加之前使用parseInt将字符串转换为数字

 function updateValue(e) { let defaultVal = e.target.dataset.val; let newVal = e.target.value; e.target.value = parseInt(defaultVal, 10) + parseInt(newVal, 10) } 
 <input type='text' value='5' data-val='5' onchange='updateValue(event)'> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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