简体   繁体   English

如何使用JavaScript或JQuery获取ASP.net中生成的控件的ID

[英]How to get IDs of Generated controls in ASP.net using JavaScript or JQuery

I have DataGrid and inside it one of the columns is a TextBox. 我有DataGrid,并且其中的一列是TextBox。 The DataGrid is generated dynamically from Database. DataGrid是从数据库动态生成的。 It is for invoicing. 用于开票。 One invoice might have two rows, another might have 10. The ID of each of these textboxes are different, and I need to read the value of each of these text boxes when the user enters an amount, add all of them up, and show the total in another field. 一张发票可能有两行,另一张发票可能有10行。每个文本框的ID是不同的,当用户输入金额时,我需要读取每个文本框的值,并将它们全部加起来并显示总数在另一个领域。

Problem: I don't know how to get to each textbox (there is ValueChanged event that fires when the user enters an amount for that specific text box) 问题:我不知道如何进入每个文本框(当用户为该特定文本框输入金额时,会触发ValueChanged事件)

I'm trying to solve this using Javascript or JQuery. 我正在尝试使用Javascript或JQuery解决此问题。 (No updatePanel) (没有updatePanel)

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thanks. 谢谢。

Give each text box a class name. 给每个文本框一个类名。 Then you can iterate through each textbox by the following 然后,您可以按照以下步骤遍历每个文本框

var total=0;

$(".className").each(function(){

    total += Number(this.val());

});

If your grid has an id of grid , then you could do: 如果您的网格的ID为grid ,则可以执行以下操作:

$('#grid input[type=text]').each(function(){
   ///Glorious code!!
});

Using jQuery, 使用jQuery,

$(document).on("ready", function(){
    $("document").on("keyup input paste", "input", function(){
        var inputID = $(this).attr('id');
        //more code here...
    });
});

Using event delegation, the event will always be fired on all textboxes. 使用事件委托,将始终在所有文本框上触发事件。 Change "input" to a more specific selector if needed. 如果需要,将“输入”更改为更具体的选择器。

Don't use IDs if you want to add listener to each of all your textbox, instead use class. 如果要将侦听器添加到所有文本框的每个中,请不要使用ID,而应使用class。

<input type="text" class="my-text-box">

and the JS(using jQuery) 和JS(使用jQuery)

$('.my-text-box').keyup(function(){
console.log($(this).val());

});

this will display the value of the textbox whenever you type something. 每当您键入内容时,这将显示文本框的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM