Create dynamic checkbox in UIWebView

2019-09-01 16:12发布

问题:

I am trying to create dynamic checkbox in UIWebView. I am using this code :

    NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"Sudhaadagdudgdada",@"qwertyuiopo",@"asdfghjkl", nil];

    for (int j = 0; j < array.count; j++)
    {
        NSString *html = [NSString stringWithFormat:@"<div id='check'></div><script> str='';   str += '<input type=\"checkbox\" name=\"one_'+i+'\"  value=\"'+%@+'\" onclick=alert(this.value); />'  document.getElementById(\"check\").innerHTML=str;</script>",[array objectAtIndex:j]];

        [self.webview loadHTMLString:[NSString stringWithFormat:@"%@",html] baseURL:nil];

    }

But there is no checkbox in UIWebView. Please help me out.

回答1:

If u want to load html in webview u need to add tags for it.Update ur code as below

NSString *html = [NSString stringWithFormat:@"<html><head><div id='check'></div><script> str='';   str += '<input type=\"checkbox\" name=\"one_'+i+'\"  value=\"'+%@+'\" onclick=alert(this.value); />'  document.getElementById(\"check\").innerHTML=str;</script></head></html>",[array objectAtIndex:j]];

//OR If u want to load javascript file as u mentioned in your code..modify as below

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"Sudhaadagdudgdada",@"qwertyuiopo",@"asdfghjkl", nil];

    for (int j = 0; j < array.count; j++)
    {
        NSString *html = [NSString stringWithFormat:@"<div id='check'></div><script> str='';   str += '<input type=\"checkbox\" name=\"one_'+i+'\"  value=\"'+%@+'\" onclick=alert(this.value); />'  document.getElementById(\"check\").innerHTML=str;</script>",[array objectAtIndex:j]];

        [webView stringByEvaluatingJavaScriptFromString:
        [NSString stringWithFormat:@"%@",html]];

    }

Hope it helps you...



回答2:

I have solved by this :

   NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"'Sudhaadagdudgdada'",@"'qwertyuiopo'",@"'asdfghjkl'", nil];
        NSString *html = [NSString stringWithFormat:@"<div id='check'></div><script> var j; var jsArray = new Array %@; str=''; for(j = 0; j< 3;  j++){ str += '<input type=\"checkbox\" name=\"one_'+j+'\"  value = \"'+jsArray[j]+'\" onclick=\"alert(this.value);\" />'+jsArray[j]+'<br/><br/>'; } document.getElementById(\"check\").innerHTML=str;</script>",array];
    NSLog(@"html..%@",html);

        [self.webview loadHTMLString:html baseURL:nil];