Global variable not working as an input value

I am a JavaScript beginner, I am stuck with a problem regarding variables.

I wrote this code :

var acNo = document.getElementById("ac").value;

function doSomething(){
    alert(acNo);
}

The output is: undefined

But when I did this :

var acNo = 3

The output is 3

Can you please tell me how can I fix it while keeping the variable global only.