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

Show/hide content depending on the value of the text field

How can I simplify the code to include all functionalities in one script? Creating separate scripts probably doesn’t make sense 🙂 I would be very grateful for your help.

document.querySelector('#country').addEventListener('change', function calculate(e) {
const div = document.querySelector('#US');
    if (Number(e.target.value) == 1)
    div.style.display = 'block';
  else
    div.style.display = 'none';
});
</script>

<script type="text/javascript">
document.querySelector('#country').addEventListener('change', function calculate(e) {
const div = document.querySelector('#DE');
    if (Number(e.target.value) == 3)
    div.style.display = 'block';
  else
    div.style.display = 'none';
});
</script>

<script type="text/javascript">
document.querySelector('#country').addEventListener('change', function calculate(e) {
const div = document.querySelector('#IT');
    if (Number(e.target.value) == 5)
    div.style.display = 'block';
  else
    div.style.display = 'none';
});
<input type="number" id="country" value="0" size="1" maxlength="1">

<div id="US" class="flag_US" style="display:none;">United States</div>
<div id="DE" class="flag_DE" style="display:none;">Germany</div>
<div id="IT" class="flag_IT" style="display:none;">Italy</div>

>Solution :

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

You can achieve that by a single change event listener, and within that listener, you can check the value and show/hide the corresponding div elements using forEach() and conditional (ternary) operator like the following way:

document.querySelector('#country').addEventListener('change', function calculate(e) {
  const selectedValue = Number(e.target.value);

  document.querySelectorAll('.flag').forEach(function(div) {
    const divValue = Number(div.getAttribute('data-value'));
    div.style.display = divValue === selectedValue ? 'block' : 'none';
  });
});
<input type="number" id="country" value="0" size="1" maxlength="1">

<div id="US" class="flag flag_US" data-value="1" style="display:none;">United States</div>
<div id="DE" class="flag flag_DE" data-value="3" style="display:none;">Germany</div>
<div id="IT" class="flag flag_IT" data-value="5" style="display:none;">Italy</div>
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