The above answers did not work for me. The below does:
document.getElementById("input_field_id").setAttribute("readonly", true);
And to remove the readonly attribute:
document.getElementById("input_field_id").removeAttribute("readonly");
And for running when the page is loaded, it is worth referring to here.