Sanela
Sanela

Reputation: 29

Javascript .focus() not working

I'm having trouble getting the javascript .focus() function to work. At this point, I'm really not sure why it's failing to execute. Could it have something to do with onload?

This is my code:

var request_brochure = function()

{
    var name = $("name").value;
    var email = $("email").value;
    var isValid = true;

    if(name == "")
    {
        $("name").focus();
        alert("Please fill in your name.");
        $("name").focus();
        isValid = false;
    }
    else if(email == "")
    {
        window.setTimeout(function(){$("email").focus();}, 100);

        alert("Please fill in your email. ");
        window.setTimeout(function(){$("email").focus();}, 100);
        isValid = false;
    }

    if(isValid)
    {
        $("form_b").submit();
        //$("brochure").innerHTML = "Request Submitted";
    }
}

window.onload = function () {   
    $("name").focus();
    $("submit1").onclick = request_brochure;

}
var $ = function (id) {
    return document.getElementById(id);
}

Any help is appreciated

Upvotes: 2

Views: 954

Answers (1)

Nicolas Straub
Nicolas Straub

Reputation: 3411

I suspect the event isn't binding correctly. window.onload does not ensure the element with id submit_1 is loaded. try adding the event to the button directly:

<input id="submit_1" onclick="request_brochure()" />

if that works then your problem is just that. Without jQuery you could mostly get away with binding the event by putting $("submit1").onclick = request_brochure; in a <script> at the end of the page, but results will be mixed from browser to browser. I'd really recommend using jQuery(function () { $("submit1").onclick = request_brochure; }) and leaving the heavy lifting of determining when the page is completely loaded to the library, since it's been tried and tested for years and is much less likely to fail than a native approach.

The comments on your question have a lot of truth, and I'd hate to see you go down the path of jQuery's high level stuff designed to make non-programmers and programmers with little javascript knowledge live's easier. With that said, the browser landscape is quite the jungle, with more than half of the world on IE 8 or lower (I could be wrong about that by now, but I'm sure it's still a considerable amount), jQuery's low level stuff (like $.ajax, $(function () {}) and the sizzle selector engine) is indispensable in my opinion. The main purposes of these utilities (jQuery's low level functions) is to address browser fragmentation issues and make devs live's easier. It's good to know the underlying code, but I'll take $.ajax over any implementation of HttpXmlRequest in a heartbeat (I still remember the days of IE6's activeX component... those were dark times). just don't do $('#some-form-field').val() without first learning document.getElementById('some-form-field').value and you should be fine :)

Upvotes: 2

Related Questions