Skip to content
Advertisement

javascript focus() not working on Firefox and IE?

I’m trying to appear a form and focus it, for some reason it only works on Chrome. How can I make it work across browsers?

<script>
function SearchCity(evt){
    document.getElementById('ciudad-eq').style.display='none';
    document.getElementById('buscarciudad').style.display='inline';
    document.getElementById("city").focus();
}
</script>    


    <div onclick="SearchCity(event)" id="ciudad-eq" style="cursor: pointer;">
    Not from Miami?
    </div>

    <div id="buscarciudad" style="display: none;">
        <form role="search" method="post" id="searchform" action="insert/insert-ip.php">
            <input type="text" id="city" name="ciudad" value="¿Cual es tu ciudad?" style="width: 140px;" >
            <input type="submit" value="ir" style="padding: 2px 6px;">
        </form>
    </div>

You can see it not working in here:

http://jsfiddle.net/CCxrp/1/

What can I do to make it work? Thanks

Advertisement

Answer

You just need to swap the order of things:

    <div onclick="SearchCity(event)" id="ciudad-eq" style="cursor: pointer;">
    Not from Miami?
    </div>

    <div id="buscarciudad" style="display: none;">
        <form role="search" method="post" id="searchform" action="insert/insert-ip.php">
            <input type="text" id="city" name="ciudad" value="¿Cual es tu ciudad?" style="width: 140px;" >
            <input type="submit" value="ir" style="padding: 2px 6px;">
        </form>
    </div>

<script>
function SearchCity(evt){
    document.getElementById('ciudad-eq').style.display='none';
    document.getElementById('buscarciudad').style.display='inline';
    document.getElementById("city").focus();
}
</script>    

The divs have to be in the DOM before JavaScript can look for them. This is the primary benefit of JQuery’s $(document).ready(function(){ ...});

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement