1
votes

I'm trying to achieve a relatively simple result - focus on a textBox when page is loaded. I use this code:

[_webView setKeyboardDisplayRequiresUserAction:NO];

NSString *javaString = [NSString stringWithFormat:@"document.getElementById('keyboard').focus()"];
NSString *result = [_webView stringByEvaluatingJavaScriptFromString:javaString];

It's called by a button click in my app. This code worked on the test page, but doesn't work on the actual site. The worst part is that I don't know any way to debug this.

Nothing happens and result is always empty string. How do I check if there's an error in JS code? Or it can't find the object? Or it can't focus on it?

UPDATE

As rightly noted by @subzero, I forgot the actual focus() method in the question. It's correct now.

1

1 Answers

2
votes

You forgot to add the focus action

document.getElementById('keyboard').focus();"

will do the trick

About checking JS errors. There are 2 ways to do it.

  1. The easy one: Add this (I'm ussing jQuery). It will show the errors at the bottom of the page

    $( document ).ready(function() {
    window.onerror = function(err) {
        log('window.onerror: ' + err)
    }
    var uniqueId = 1
    function log (message, data) {
            var log = document.getElementById('log')
            var el = document.createElement('div')
            el.className = 'logLine'
            el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data)
            if (log.children.length) { log.insertBefore(el, log.children[0]) }
            else { log.appendChild(el) }
    }
    

in your html:

<div id='log'></div>
  1. See this What are some methods to debug Javascript inside of a UIWebView?