Uncaught SyntaxError: Identifier ‘country_states’ has already been declared

Issue

This Content is from Stack Overflow. Question asked by Salih Sultan

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>



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?