Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to have javascript update an input value on a page before the page loads?

I have an <input id="my_field" type="number"> element on a page.

I have this code on my page:

$(document).ready(function() {
    $("#my_field").val(parseInt($("#my_field").val()) + 1);
});

This works, but looks unprofessional. When the page loads, the <input> field loads with the original value, and half a second later, updates to the new, incremented value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to make it increment the value before its initially drawn by the browser, so that the original value doesn’t flash on the screen?

>Solution :

You don’t need to wait for $(document).ready – you only need to wait for the input to exist.

You can have the script run soon after the <input> in the HTML, eg:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="my_field" type="number" value="5">
<!-- make sure there isn't a whole lot of code/markup in between -->
<script>
$("#my_field").val(parseInt($("#my_field").val()) + 1);
</script>

You can also insert the script beforehand, and use a MutationObserver to wait for the <input> to exist, though this technique should only be needed for large pages when there’s too much content, and the script and input can’t be put close to each other.

<script>
new MutationObserver((_, observer) => {
  const my_field = document.querySelector('#my_field');
  if (!my_field) return;
  my_field.value = Number(my_field.value) + 1;
  observer.disconnect();
})
  .observe(document.body, { childList: true, subtree: true });
</script>
<input id="my_field" type="number" value="5">

There’s no need to require a big library like jQuery in order to do something so trivial – not having to load a big library will reduce load times in some cases.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading