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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10120834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:56:05  来源:igfitidea点击:

How to get the text value from textbox which is in Gridview using Javascript

javascriptasp.netgridview

提问by Developer

Hi all I have written the following script to get the value from the textboxwhich is in GridViewbut I am getting some value as NaNcan some one tell where I went wrong

大家好,我已经编写了以下脚本来获取其中的值textboxGridView但是我得到了一些值,因为NaN有人可以告诉我哪里出错了

This is my sample script

这是我的示例脚本

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;
                    }
                }
            }

My grid is as follows

我的网格如下

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

Like that some empty rows will also be there I need to sum the Amountand display

就像一些空行也会在那里我需要总结Amount和显示

My grid view

我的网格视图

<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>

My original script initially I will add AMount in the grid view based on user quantity after that I Would like to display the total amount in the grid to a label

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

<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>

回答by Developer

After all here is the solution

毕竟这里是解决方案

<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>

回答by Coder

There is a problem in your code, Javascript's indexOf()either returns -1 or positive integer, valueis the property of input textbox and has nothing to do with indexOf().

你的代码有问题,JavascriptindexOf()要么返回 -1 要么返回正整数,value是输入文本框的属性,与indexOf().

Replace your code with this:

用这个替换你的代码:

    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());
            }
        }
    }

回答by Vishal Suthar

I think the method you are using is wrong. better to use something as below one:

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

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;
    }
}

回答by lakshmi

Text inside the gridview

网格视图中的文本

    <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>

Javascript code

Javascript代码

    function findcontrol()
      {
          var textBoxQuantity = document.getElementsByClassName("field-text1");
for (var i = 0; i < textBoxQuantity.length; i++) {
              findvalue(textBoxQuantity[i].id);
          }
      }
function findvalue()
{
var Quantity = document.getElementById(quantity).value;
if (Number(Quantity) > 0){
// your calculations here
}

回答by Foysal Ahmed

I think this will work easily to read Grid view data

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

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 -->