Ondřej Javorský
Ondřej Javorský

Reputation: 475

How to change variable inside jQuery function and read it outside that function

How can I change variable inside jQuery function to make possible read it outside, for example print it to html. Becouse when I tried to change select option content of debug div didn't change. Why doesn't it work?

My code:

$(document).ready(function() {
  var day;
  var month;
  var year;

  $('#day').change(function() {
    day = true;
  });

  $('#month').change(function() {
    month = true;
  });

  $('#year').change(function() {
    year = true;
  });

  document.getElementById('debug').innerHTML = day + month + year;

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="input-group">
  <select class="custom-select" id="den">
    <option value="Den" disabled selected hidden>Den</option>
    <?php foreach ($datum['dny'] as $dny) : ?>
    <option value="<?= $dny ?>"><?= $dny ?></option>
    <?php endforeach ?>
  </select>
  
  <select class="custom-select" id="mesic">
    <option value="Měsíc" disabled selected hidden>Měsíc</option>
    <?php foreach ($datum['mesice'] as $cislo => $nazev) : ?>
    <option value="<?= $cislo ?>"><?= $nazev ?></option>
    <?php endforeach ?>
  </select>
  
  <select class="custom-select" id="rok">
    <option value="Rok" disabled selected hidden>Rok</option>
    <?php foreach ($datum['roky'] as $roky) : ?>
    <option value="<?= $roky ?>"><?= $roky ?></option>
    <?php endforeach ?>
  </select>
</div>

DEBUG:
    <div id="debug">

    </div>

Thank you for your helps.

Upvotes: 1

Views: 241

Answers (1)

user9366559
user9366559

Reputation:

You need to have each function check to see if all the vars are filled out, and then set the content if so.

Use a separate function to keep it short.

$(document).ready(function() {
  var day;
  var month;
  var year;

  $('#day').change(function() {
    day = this.value;
    check();
  });

  $('#month').change(function() {
    month = this.value;
    check();
  });

  $('#year').change(function() {
    year = this.value;
    check();
  });

  function check() {
    if (day && month && year) {
      document.getElementById('debug').innerHTML = `${day}-${month}-${year}`;
    }
  }
});
pre {
  font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Day
<select id=day><option>
<option>1 <option>2 <option>3
</select> Month
<select id=month><option>
<option>1 <option>2 <option>3
</select> Year
<select id=year><option>
<option>2018 <option>2019 <option>2020
</select>

<pre id=debug></pre>

Upvotes: 3

Related Questions