1

Hi all i have code that reads from a DB and populates a string in the code behind

List<string> rows = new List<string>();
    DataTable prods = common.GetDataTable("vStoreProduct", new string[] { "stpt_Name" }, "stpt_CompanyId = " + company.CompanyId.ToString() + " AND stpt_Deleted is null");

    foreach (DataRow row in prods.Rows)
    {

        prodNames += "\"" + row["stpt_Name"].ToString().Trim() + "\",";
    }
    string cleanedNanes =  prodNames.Substring(0, prodNames.Length - 1);
    prodNames = "[" + cleanedNanes + "]";

This produces something like ["Test1","Test2"]

In javascript i have

var availableTags = '<% =prodNames %>';

alert(availableTags);

How can i access this like an array in javascript like

alert(availableTags[5]);

and get the full item at the given index.

Thanks any help would be great

3 Answers 3

2

Get rid of the quotes:

var availableTags = <% =prodNames %>;

With the quotes there, you're creating a JavaScript string. Without them, you've got a JavaScript array constant.

1
  • 1
    Thanks for this @Pointy - Even though I answered this question I just learnt something new (Confirmed in js console). Commented Sep 19, 2011 at 16:12
0

You're going to have to split the variable from .NET into a JS array.

Check out: http://www.w3schools.com/jsref/jsref_split.asp

Example based on your code:

var availableTags = '<% =prodNames %>';
var mySplitResult = availableTags .split(",");
alert(mySplitResult[1]);
2
  • This is silly; why not just leave out the quotes from the variable initialization in the first place? Also, please consider avoiding w3schools.com. Commented Sep 19, 2011 at 16:07
  • considering he has the surrounding [ and ], yes he'd have an array, versus just a string. Commented Sep 19, 2011 at 16:10
0

I believe split() will do what you want:

    var availableTagsResult = availableTags.split(",");
    alert(availableTagsResult[1]) //Display element 1

This will create an array from the string which has been split on ,

4
  • And what about the square brackets? Commented Sep 19, 2011 at 16:08
  • I'm not providing an exact solution - rather pointing the OP in the right direction Commented Sep 19, 2011 at 16:09
  • Well, if the OP simply initialized the variable without the single quotes, then it would be an array without any need for string manipulation. Commented Sep 19, 2011 at 16:10
  • @Pointy - Thanks, I didn't know that, you've earned by upvote Commented Sep 19, 2011 at 16:10

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.