如何用C#代码编写Javascript编码? [英] How to write Javascript coding in C# code behind?
本文介绍了如何用C#代码编写Javascript编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在动态创建文本框,以便如何在textbox'onchange'事件下面调用javascript函数?
i想要计算两个动态创建的文本框值。
i am creating textboxes dynamically so how to call below javascript function for textbox 'onchange' event?
i want to calculate two dynamically created textboxes values.
<script type="text/javascript">
debugger;
function myFunction() {
var btn = document.getElementById('<%= temp.ClientID%>').value;
var btntemp = document.getElementById('<%= txttemp2.ClientID%>').value;
var val = parseInt(btn) + parseInt(btntemp);
document.getElementById('<%= TextBox1.ClientID%>').value = val;
}
</script>
<asp:TextBox ID="temp" runat="server" onchange="myFunction()"></asp:TextBox>
<asp:TextBox ID="txttemp2" runat="server" onchange="myFunction()"></asp:TextBox>
推荐答案
您可以将其设置为属性
You can set it as attribute
txt_box.Attributes.Add("onchange", "myFunction(this);");
同时将您的函数更改为接受文本框作为参数
Also change your function to accept text box as parameter
function myFunction(control) {
alert(control.id);
}
如果您需要获取文本框值的总和,可以从代码隐藏中设置文本框的类名,如下所示< br $>
if you need to get sum of textbox values, you can set class name for textboxes from codebehind as below
protected void Button1_Click(object sender, EventArgs e)
{
Table table = new Table();
table.ID = "Table1";
PlaceHolder1.Controls.Add(table);
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
row.ID = "Row_" + i;
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i ;
tb.CssClass = "sum";
cell.Controls.Add(tb);
tb.Attributes.Add("onchange", "myFunction();");
row.Cells.Add(cell);
table.Rows.Add(row);
}
}
然后您可以按类名使用查找控件并计算总和如下
then you can use find control by class name and calculate the sum as below
function myFunction() {
var sum = 0;
var elements = document.getElementsByClassName("sum");
for (var i = 0, length = elements.length; i < length; i++) {
if (elements[i].value) {
sum = sum + (parseInt(elements[i].value) || 0);
}
}
document.getElementById('<%= TextBox1.ClientID%>').value = sum;
}
这篇关于如何用C#代码编写Javascript编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文