Starting off I have UTFS.
Trying to insert a variable in the middle of string to populate a web view form without using a string by append and making the code huge. My current code is
NSString *html = [webView stringByEvaluatingJavaScriptFromString:@” document.DetailView.innerHTML;” @”document.getElementsByName(‘user_name’)[0].value = ‘somuser’;”
@”document.getElementsByName(‘user_password’)[0].value = ‘somevar’;”
@”document.DetailView.submit();” ]
I have tried
NSString *html = [webView stringByEvaluatingJavaScriptFromString:@” document.DetailView.innerHTML;” @”document.getElementsByName(‘user_name’)[0].value = ‘%@’;”
@”document.getElementsByName(‘user_password’)[0].value = ‘somevar’;”
@”document.DetailView.submit();” , txtField.text];
But it throws me a build error(specifically it’s looking for “]”). I’m guessing I will have to slowly build the string using stringbyappend but i’m hoping for a little luck that someone will have encountered this or have a workaround for it. This seemed so simple in c#.
You can place variables into a string with
stringWithFormat:. In your case, the following would work:There is an additional bug in your code in that you don’t properly encode the text field value – consider what would happen if the user entered an apostrophe.
However building up JavaScript in this way isn’t a great approach. Consider factoring out the JavaScript into an external JavaScript file – this will make it much easier to read and write.