如何使用Javascript从Gridview中的文本框中获取文本值

时间:2012-04-12 09:23:28

标签: javascript asp.net gridview

大家好我已经编写了以下脚本来获取textbox GridView中的NaN的值,但我得到了一些价值var grid = document.getElementById("<%=grdInvoice.ClientID%>"); var inputs = grid.getElementsByTagName("input"); for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == "text") { if (inputs[i].name.indexOf("txtAmount").value != "") { alert("Not Null"); amnt = parseInt(inputs[i].name.indexOf("txtAmount").value); alert(amnt.toString()); // Getting Nan here //var v = document.getElementById('<%= lblTotal.ClientID %>').value; } } } 可以告诉我哪里出错了

这是我的示例脚本

 ddl    Quantity  desc     Rate    Amount
        1         d        10      10
        2         d        20      40

我的网格如下

Amount

就像那些空行也在那里我需要总结<asp:GridView ID="grdInvoice" runat="server" AutoGenerateColumns="False" GridLines="None" Width="650px" CellPadding="2" CellSpacing="1" ForeColor="#333333" CssClass="inv_grid_data" OnSelectedIndexChanged="grdInvoice_SelectedIndexChanged" OnSelectedIndexChanging="grdInvoice_SelectedIndexChanging" Style="font-family: verdana; font-size: 9px;"> <RowStyle BackColor="#f1f1f2" ForeColor="#333333" BorderColor="#333333" BorderStyle="Solid" BorderWidth="1px" /> <HeaderStyle CssClass="inv_grid_hed" BackColor="#f2f2f2" ForeColor="black" Font-Names="Verdana,Arial,Helvetica,sans-serif" Font-Size="9px" Height="15px" Font-Bold="false" /> <AlternatingRowStyle CssClass="tr2" BackColor="White" ForeColor="#284775" /> <Columns> <asp:TemplateField HeaderText="Item Name" HeaderStyle-Width="140"> <ItemTemplate> <asp:DropDownList ID="ddlItems" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlItems_SelectedIndexChanged" DataTextField="LineItemName" DataValueField="LineItemName" CssClass="txt_box_ssm_drop" Width="100%" Font-Names="Verdana,Arial,Helvetica,sans-serif" Font-Size="12px"> </asp:DropDownList> </ItemTemplate> <HeaderStyle Width="180px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="txtQuantity" CssClass="txt_box_ssm_big" runat="server" Width="100%"></asp:TextBox> </ItemTemplate> <HeaderStyle Width="100px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Description"> <ItemTemplate> <asp:TextBox ID="txtDescription" CssClass="txt_box_ssm_big" runat="server" Width="100%"></asp:TextBox> </ItemTemplate> <%--<ItemStyle Height="11px" Width="100px" /> --%> <HeaderStyle Width="260px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Rate"> <ItemTemplate> <asp:TextBox ID="txtRate" ReadOnly="true" CssClass="txt_box_ssm_big" runat="server" Width="100%"></asp:TextBox> </ItemTemplate> <HeaderStyle Width="100px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Amount"> <ItemTemplate> <asp:TextBox ID="txtAmount" runat="server" CssClass="txt_box_ssm_big" Width="100%"></asp:TextBox> <%--<asp:Label ID="lblamount" runat="server" Text='<%# Eval("Amount") %>'/>--%> </ItemTemplate> <HeaderStyle Width="100px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Delete"> <ItemTemplate> <%--<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/icon_delete.gif" OnClick="RowDelete_Click" OnClientClick="msg('Can you get there from here?','This is a Title')"/>--%> <asp:ImageButton ID="RowDelete" runat="server" ImageUrl="~/images/icon_delete.gif" OnClick="RowDelete_Click" OnClientClick="return showConfirm()" Style="margin-left: 15px;" /> </ItemTemplate> </asp:TemplateField> <asp:CommandField ShowSelectButton="true" ButtonType="image" SelectImageUrl="~/Invoiceimages/Copy-32(1).png" SelectText="Copy" HeaderText="Copy" /> </Columns> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <EditRowStyle BackColor="#999999" /> </asp:GridView> 并显示

我的网格视图

<script type="text/javascript">
        function multiplication(txtQuantity, txtRate, txtAmount) {
            var weight = document.getElementById(txtQuantity).value;
            var rate = document.getElementById(txtRate).value;
            document.getElementById(txtAmount).value = weight * rate;
            var amnt = 0;
//            var Grid_Table = document.getElementById('<%= grdInvoice.ClientID %>');
//            for (var row = 1; row < Grid_Table.rows.length; row++) {

//                var qty = 0;

//                for (var col = 0; col < Grid_Table.rows[row].cells.length; col++) {

//                    var cellcollectin = Grid_Table.rows[row].cells[col];

//                    for (var j = 0; j < cellcollectin.childNodes.length; j++) {

//                        if (cellcollectin.childNodes[j].type == "text") {

//                            if (cellcollectin.childNodes[j].name.indexOf("txtAmount") > 1) {
//                                if (cellcollectin.childNodes[j].value != "") {
//                                    qty = parseInt(cellcollectin.childNodes[j].value);
//                                    amnt = amnt + qty;
//                                }
//                            }
//                        }
//                    }
//                }
//            }
                        var grid = document.getElementById("<%=grdInvoice.ClientID%>");
                        var inputs = grid.getElementsByTagName("input");
                        for (var i = 0; i < inputs.length; i++) {
                            if (inputs[i].type == "text") {
                                if (inputs[i].name.indexOf("txtAmount").value != "") {
                                    alert("Not Null");
                                    amnt = grid.rows[i].cells[1].childNodes[0].value;
                                    //amnt = parseInt(inputs[i].name.indexOf("txtAmount").value);
                                    alert(amnt.toString());
                                    //var v = document.getElementById('<%= lblTotal.ClientID %>').value;
                                }
                            }
                        }
            document.getElementById('<%= lblTotal.ClientID %>').innerHtml = amnt.toString();
        }
    </script>

我的原始脚本最初我会根据用户数量在网格视图中添加AMount,之后我想在网格中显示标签的总金额

{{1}}

5 个答案:

答案 0 :(得分:4)

毕竟这是解决方案

<script type="text/javascript">
    function multiplication(txtQuantity, txtRate, txtAmount) {
        var col1;
        var totalcol1 = 0;
        var weight = document.getElementById(txtQuantity).value;
        var rate = document.getElementById(txtRate).value;
        document.getElementById(txtAmount).value = weight * rate;
        var grid = document.getElementById('<%=grdInvoice.ClientID %>');


        for (i = 0; i < grid.rows.length; i++) {
            col1 = grid.rows[i].cells[4];
            //col2 = grid.rows[i].cells[1];

            for (j = 0; j < col1.childNodes.length; j++) {
                if (col1.childNodes[j].type == "text") {
                    if (!isNaN(col1.childNodes[j].value) && col1.childNodes[j].value != "") {
                        totalcol1 += parseInt(col1.childNodes[j].value)
                    }
                }
            }
        }
        document.getElementById('<%= lblTotal.ClientID %>').innerHTML = totalcol1.toFixed(2).toString();
    }
</script>

答案 1 :(得分:1)

您的代码存在问题,Javascript的indexOf()要么返回-1,要么返回正整数,value是输入文本框的属性,与indexOf()无关。

用以下代码替换您的代码:

    var grid = document.getElementById("<%=grdInvoice.ClientID%>");
    var inputs = grid.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "text") {
            if (inputs[i].name == "txtAmount" || inputs[i].id == "txtAmount") {
                amnt = parseInt(inputs[i].value);
                alert(amnt.toString());
            }
        }
    }

答案 2 :(得分:0)

我认为您使用的方法是错误的。最好使用以下内容:

var inputs = grid.getElementsByTagName("input");
var grid = document.getElementById('<%= grdInvoice.ClientID %>');

for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == "text") {         
        amnt = parseInt(grid.rows[i].cells[2].childNodes[0].value;);
        alert(amnt.toString()); // Getting Nan here
        //var v = document.getElementById('<%= lblTotal.ClientID %>').value;
    }
}

答案 3 :(得分:0)

gridview中的文字

@Audited(withModifiedFlag=true)
@Entity
@SecondaryTable(name = "ParentChild")
public class ParentChild{

    // @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
    @NotAudited
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "ParentChild", joinColumns = {
        @JoinColumn(name = "parent_id", nullable = false, updatable = false) },
        inverseJoinColumns = {
        @JoinColumn(name = "child_id", nullable = false, updatable = false) })
    protected Set<ParentChild> pc;
    ...
}

Javascript代码

    <asp:GridView ID ="grvAddItems" runat="server">
<asp:TemplateField HeaderText="Quantity">
            <ItemTemplate>
                <asp:TextBox CssClass="field-text1"  Width="70 px" ID="txtQuantity" runat="server" TextMode="Number"  onblur="findcontrol()"></asp:TextBox>
            </ItemTemplate>
            </asp:TemplateField>
</asp:GridView>

答案 4 :(得分:0)

我认为这很容易读取Grid视图数据

function StatusValidation() {
var rowCount = <%=gvRoomStatus.Rows.Count%>; // set your grid view name
for (var i = 0; i < rowCount; i++) {
var checkBoxes = $("#ContentPlaceHolder1_gvRoomStatus_chkIsSavePermission_" +i).is(":checked");
if (checkBoxes == true) {
count++;
var ddlHKRoomStatus = $("#ContentPlaceHolder1_gvRoomStatus_ddlHKRoomStatus_" + i).val();
var fromDate = $("#ContentPlaceHolder1_gvRoomStatus_txtFromDate_" + i).val();
var fromTime = $("#ContentPlaceHolder1_gvRoomStatus_txtFromTime_" + i).val();
var toDate = $("#ContentPlaceHolder1_gvRoomStatus_txtToDate_" + i).val();
var toTime = $("#ContentPlaceHolder1_gvRoomStatus_txtToTime_" + i).val();
var reason = $("#ContentPlaceHolder1_gvRoomStatus_txtReason_" + i).val();
  if (ddlHKRoomStatus == "3" || ddlHKRoomStatus == "4") {
       if (fromDate == "") {
       toastr.warning("Please provide From Date");
       $("#ContentPlaceHolder1_gvRoomStatus_txtFromDate_" + i).focus();
       return false;
                            }
                            else if (fromTime == "") {
                                toastr.warning("Please provide From Time");
                                $("#ContentPlaceHolder1_gvRoomStatus_txtFromTime_" + i).focus();
                                return false;
                            }
                            else if (toDate == "") {
                                toastr.warning("Please provide To Date");
                                $("#ContentPlaceHolder1_gvRoomStatus_txtToDate_" + i).focus();
                                return false;
                            }
                            else if (toTime == "") {
                                toastr.warning("Please provide To Time");
                                $("#ContentPlaceHolder1_gvRoomStatus_txtToTime_" + i).focus();
                                return false;
                            }
                            else if (reason == "") {
                                toastr.warning("Please provide a valid reason");
                                $("#ContentPlaceHolder1_gvRoomStatus_txtReason_" +i).focus();
                                return false;
                            }
                        }
                        

                    }
}

<!-- begin snippet: js hide: false console: true babel: false -->