1

I have multiple textboxes added dynamically through jQuery. But due to some reasons, the id of some textboxes is missing.

I want to make a check on all the textboxes if they have their IDs or not. If not then add it using C#.

I have done this part from backend:

// Say I have 3 textboxes added in string "Question" here. 

string Question="<input data-size="0" data-type="0" id="Answer1" placeholder="Answer1" type="text" /><br/>
<br/>
<input data-size="0" data-type="0" id="Answer2" placeholder="Answer2" type="text" /><br/>
<br/>
<input data-size="0" data-type="0" id="Answer3" placeholder="Answer3" type="text" /><br/>
<br/>
&nbsp;";

string textboxTagPattern= @"(<input)([^>]*)(type=\"")(text)(\"")([^>]*)(/>)";
Regex rgx = new Regex(textboxTagPattern, RegexOptions.IgnoreCase);
MatchCollection questionInputText = rgx.Matches(Question);

string textboxes ="";

if (questionInputText.Count > 0){
    for (int i = 0; i < questionInputText.Count; i++)
    {
        textboxes = questionInputText[i].Value;
        var id = textboxes.IndexOf("id");
        if (textboxes.IndexOf("id") == -1)
        {
            I am stuck here. How to add the id attribute to the textboxes?
        }
    }
} 
Viveka
  • 340
  • 2
  • 14
  • 3
    Generally speaking, you shouldn't use regex to parse HTML. It's a [bad idea](https://stackoverflow.com/a/1732454/8967612). But [why not?](https://stackoverflow.com/a/590789/8967612) Here are [some examples](https://stackoverflow.com/a/18724992/8967612) to illustrate. Use an [HTML parser](https://stackoverflow.com/q/56107/8967612) instead. – 41686d6564 stands w. Palestine Aug 24 '20 at 10:44
  • use JQuery's .Prop() method. – Captain Kenpachi Aug 24 '20 at 11:02
  • Could you add the web rendering technology your using in the c# web application? https://en.wikipedia.org/wiki/ASP.NET includes the evolution over time. Web Forms, MVC, Razor, Single Page Application (Angular, React, Vue). – Jamie Clayton Aug 24 '20 at 11:31

1 Answers1

0

You can use String.Insert(int startIndex, string value) like below. Use appropriate value instead of Answer1 in "id=\"Answer1\" ".

if (textboxes.IndexOf(\"id\") == -1)
{
    textboxes = textboxes.Insert(textboxes.IndexOf("<input ") + "<input ".Length, "id=\"Answer1\" ");
}
Karan
  • 12,059
  • 3
  • 24
  • 40