1

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 Answer 1

2

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?
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the debugging tips. And of course I forgot the focus() action in the question, it's there in the actual code.

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.