问题
HI,
I need to calculate values of two textboxex in gridview and display the result in the third textbox using javascript as soon as the value entered in second textbox.
my textbox fields are: Quantity and Price The result should be displayed in Total.
that is, (Total)Value= Quantity * Rate.
I have tried this, CODE BEHIND:C#
protected void gvPOItms__RowCreated(Object sender, GridViewRowEventArgs e)
{
try
{
TextBox txt1 = (TextBox)e.Row.FindControl("txtQty");
TextBox txt2 = (TextBox)e.Row.FindControl("txtRate");
TextBox txt3 = (TextBox)e.Row.FindControl("txtValue");
txt1.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
txt2.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
}
catch (Exception ex)
{
Response.Write(ex);
}
}
JAVASCRIPT:
<Script type="text/javascript">
function multiplication(tx1,txt2,txt3)
{
//Your logic for multiplication
var Qty=document.getElementById(txt1).value;
var Rate=document.getElementById(txt2).value;
document.getElementById(txt3).value=Qty*Rate;
}
</script>
Markup Page:
But, i couldn't get the answer, its not throwing any error.
Can someone tell me what's wrong?
回答1:
you should change string to int (as value of any textbox returns string) before multiplication :)
try this :-
txt1.Attributes["onKeyup"] = "javascript: return multiplication('" + Convert.ToInt32(txt1.Text) + "','" + Convert.ToInt32(txt2.Text) + "','" + Convert.ToInt32(txt3.ClientID) + "')";
txt2.Attributes["onKeyup"] = "javascript: return multiplication('" + Convert.ToInt32(txt1.Text) + "','" + Convert.ToInt32(txt2.Text) + "','" + Convert.ToInt32(txt3.ClientID) + "')";
In script :-
<Script type="text/javascript">
function multiplication(Qty,Rate,txt3)
{
//Your logic for multiplication
document.getElementById(txt3).value=Qty*Rate;
}
</script>
回答2:
The problem is with these lines of code
txt1.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
txt2.Attributes["onKeyup"] = "javascript: return multiplication('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')";
Use Add method instead
txt1.Attributes.Add("onKeyup", "javascript: return multiplication('" +
txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')");
txt2.Attributes.Add("onKeyup", "javascript: return multiplication('" +
txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')");
and also do parseInt() in javascript
var Qty = parseInt(document.getElementById(txt1).value);
var Rate = parseInt(document.getElementById(txt2).value);
来源:https://stackoverflow.com/questions/5441892/auto-multiply-two-column-in-gridview