1

How can I access the similar asp control id's by using for loop? I have the following asp text boxes.

<asp:TextBox ID="PFtxtname1" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname2" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname3" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname4" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname5" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname6" runat="server"></asp:TextBox>

and I want to access all these text box value through for loop using jQuery, how can I do?

I am tried to get the value by below code, but it shows error.

var ar_val=[];
for(i=0;i<7;i++)
{
  var txtv = $("#<%=PFtxtname"+i+".ClientID%>").val().trim();
  ar_val.push(txtv);
}
0

2 Answers 2

4

You are mixing client side and server side code, it will not work this way.

add a commom css class to textboxes :

<asp:TextBox ID="PFtxtname1" runat="server" CssClass="txtName"></asp:TextBox>

and iterate on elements in Jquery using class selector:

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

    alert($(this).val()) // for value
    alert(this.id)   // for id

})
Sign up to request clarification or add additional context in comments.

7 Comments

Just a question: what if the jquery code is inside the markup file? Mixing code is still unhealthy, however, it should work then.
Yes we can write Jquery code in markup file inside script tag, better way is to use a separate js file, and i was talking about OP using c# statements inside Jquery/javascript
It is certainly better to separate the code, BUT if the script is inside the markup, then you can use C# code there if I am not mistaken. At least you can do this with PHP. I do not remember how it was in C#, since I did not work with the language for a long time, but it would not make sense to not have this possibility.
We can use to some extent, server side values are evaluated on page load, you cannot do like above to use javascript for loop and execute c# statements as c# code gets executed on page load while in js that's not the case
So we are in agreement that mixing client-side with server-side can work if the script is inside the markup, yet server-side code is executed before the page is sent to the client. I believe you should edit your answer to reflect this.
|
0

you should try this i think its working fine

var ar_val=[]; 
    $("form").find("[id$='PFtxtname']").each(function () {

            var txtv =  $(this).val().trim();  
    ar_val.push(txtv);    
                });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.