Uncaught SyntaxError: Identifier 'country_states' has already been declared

Viewed 38

I am trying to create a form and add "country-state" dynamic list select. The code itself works when I try it apart from the form itself and open it in new html. But when I copy the code into the form itself it gives this error. error link. Could you please help?

<div class="wrapper">
  <select id="countries">
    <option value="-1">Select Country</option>
    <option value="1">Adana</option>
    <option value="2">Adıyaman</option>
  </select>

  <select name="" id="states">
    <option value="-1">Select State</option>

  </select>
</div>

<script type="application/javascript">
  let country_states = [{
      country: "Adana",
      code: "1",
      states: ["Aladağ", "Ceyhan", "Çukurova", "Feke", "İmamoğlu", "Karaisalı", "Karataş", "Kozan", "Pozantı", "Saimbeyli", "Sarıçam", "Seyhan", "Tufanbeyli", "Yumurtalık", "Yüreğir"]
    },
    {
      country: "Adıyaman",
      code: "2",
      states: ["Merkez", "Besni", "Çelikhan", "Gerger", "Gölbaşı", "Kahta", "Samcak", "Sincik", "Tut"]
    }
  ]

  let countryselect = document.querySelector('#countries');
  let stateselect = document.querySelector('#states');

  countryselect.onchange = function() {
    stateselect.options.length = 0;
    if (countryselect.value != -1) {
      for (ele of country_states) {
        if (countryselect.value == ele.code) {

          let states = ele.states
          let op = document.createElement('option');
          op.value = -1;
          op.innerText = "Select State"
          stateselect.options[0] = op;
          let i = 1;
          for (state of states) {
            let op = document.createElement('option');
            op.value = state;
            op.innerText = state;
            stateselect.options[i] = op;
            i++

          }
        }

      }

    }
  }


  // 1,2,3,4,5,6,7
  // 1,2,3,4,5,6
</script>

1 Answers

Take very good look at you code

  • search it for second "country-state" or "country_state" declaration
  • be more specific "-" or "_"
  • use const for country_states in your code

this is some of the issues i just want to share with you, maybe not the solution for now but will be in good use for you in the future.

Related