[英]set value of a text box from another text box in html5 asp.net
I have 3 text boxes in my mvc4 asp.net View. 我在mvc4 asp.net视图中有3个文本框。
Code is:- 代码是:-
<table>
<tr><td>A:</td><td>@Html.TextBox("A")</td></tr>
<tr><td>B:</td><td>@Html.TextBox("B")</td></tr>
<tr><td>Answer:</td><td>@Html.TextBox("C")</td></tr>
</table>
For Example,What i want is, 例如,我想要的是
As soon as i enter "3" in TextBox A and "2" in TextBox B, the answer "5" should be displayed instantly in TextBox C, without me hitting any submit button. 一旦我在文本框A中输入“ 3”,在文本框B中输入“ 2”,答案“ 5”应立即显示在文本框C中,而无需单击任何提交按钮。
How can i do this? 我怎样才能做到这一点?
Thank You. 谢谢。
You need to use some form of Javascript to do this. 您需要使用某种形式的Javascript来执行此操作。 Here is a piece of vanilla JavaScript which adds an event handler onto both A and B, which compares the value of the textboxes and displays the required value in C if the condition is met:
这是一段原始的JavaScript,它将事件处理程序添加到A和B上,该事件处理程序将比较文本框的值,并在满足条件的情况下在C中显示所需的值:
// Get all the textboxes by their IDs
var textboxA = document.getElementById("A");
var textboxB = document.getElementById("B");
var textboxC = document.getElementById("C");
// Add a handler for the keyup event
textboxA.addEventListener("keyup", showAnswer, false);
textboxB.addEventListener("keyup", showAnswer, false);
function showAnswer() {
// Convert the values from a string to a float
var valA = parseFloat(textboxA.value);
var valB = parseFloat(textboxB.value);
// Make sure both values are valid numbers
if(!isNaN(valA) && !isNaN(valB)) {
// Show the calculated value in the C box
textboxC.value = valA + valB;
}
else {
// Can't do any calculations, just show a blank value
textboxC.value = "";
}
}
Here is a fiddle to demonstrate. 这是一个小提琴来演示。
There are easier ways of doing this with jQuery: 使用jQuery可以有更简单的方法:
$(function() {
$("#A, #B").on("keyup blur", function() {
var valA = parseFloat($("#A").val());
var valB = parseFloat($("#B").val());
if(!isNaN(valA) && !isNan(valB)) {
$("#C").val(valA + valB);
}
else {
$("#C").val("");
}
});
});
Here another solution using JQuery 这是另一个使用JQuery的解决方案
For using JQuery you need to add JQuery lib in your head tag , just copy paste the below line in head tag. 要使用JQuery,您需要在head标签中添加JQuery lib,只需将以下行复制粘贴到head标签中即可。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
JQuery: jQuery的:
<script type="text/javascript" >
$(document).ready(function (){
$("#Txt_1").on('input', function () {
sumCal();
});
$("#Txt_2").on('input', function () {
sumCal();
});
function sumCal() {
var txt1 = $("#Txt_1").val();
var txt2 = $("#Txt_2").val();
var result = Number(txt1) + Number(txt2);
$("#Txt_3").val(result);
}
});
</script>
Try this 尝试这个
$(document).ready(function(){
$("#txtbox2").keyup(function(){
var txt01= parseInt ($("#txtbox1").val(),10);
var txt02= parseInt( $("#txtbox2").val(),10);
$("#txtbox3").val( txt01+txt02);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.