1

I am trying to run a javascript from a UIWebView. The javascript function I want to run is the one below

function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
    if(sel.options[i].innerHTML === val) {
       sel.selectedIndex = i;
       break;
    }
}

}

I know you can execute javascript in UIWebView using

(NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

So i form the javascript string as

NSString *str = @"function SelectAnimal() {\
    var sel = document.getElementById('Animals');\
    var val = document.getElementById('AnimalToFind').value;\
    for(var i = 0, j = sel.options.length; i < j; ++i) {\
        if(sel.options[i].innerHTML === val) {\
            sel.selectedIndex = i;\
            break;\
        }\
    }\
}";

and run the javascript as

[webView stringByEvaluatingJavaScriptFromString:str];

But this doesnt seem to work. Is there something i'm doing wrong?

1 Answer 1

4

Looks like your javascript is only defining the function, but never calling it.

Try changing to:

NSString *str = @"function SelectAnimal() {\
    var sel = document.getElementById('Animals');\
    var val = document.getElementById('AnimalToFind').value;\
    for(var i = 0, j = sel.options.length; i < j; ++i) {\
        if(sel.options[i].innerHTML === val) {\
            sel.selectedIndex = i;\
            break;\
        }\
    }\
}\
selectAnimal();";
Sign up to request clarification or add additional context in comments.

1 Comment

That was really dumb. I'm almost embarrassed. Thanks buddy!

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.