Skip to content

populate select on page load

I’ve got it working for the first element, but as soon as i try to press another element it repopulates itself and selects the first element.

HTML:

<select id="line" name="line">
    <option selected="selected" disabled="true">Auswahl...</option>
</select>

Population:

$(document).ready(function(){
    var lineselects = document.getElementsByName("line");
    lineselects.forEach($line => $line.addEventListener('click', popLines));
    
});
function popLines(){
    fetch('ajax0.php',{method:'post'})
        .then( r=>r.json() )
        .then( json=>{
            line.innerHTML='';
            Object.keys( json ).forEach( key=>{
                let obj=json[ key ];
                line.append( new Option( obj.line, obj.line ) );
            })
        })
};

Necessary Information: I need to add the EventListener to every element of the NodeList as every Element is a select that needs to be populated. Should I split the populations up or is this fine too?

How do I prevent it from repopulating the select?

EDIT: For anyone stumbling on this answer, don’t use the EventListener on every element of the NodeList, use the document.ready for every select you want to populate seperately -> if you press on any other element of the NodeList, only the first will get populated.

Answer

You are emptying the line <select> element empty with each fetch, but it looks like you want to empty it only for the first time, the best way I can think of is to use some sort of flag so that you know it’s the first time.

$(document).ready(function(){
    var lineselects = document.getElementsByName("line");
    lineselects.forEach($line => $line.addEventListener('click', popLines));
    
});
function popLines(){
    fetch('ajax0.php',{method:'post'})
        .then( r=>r.json() )
        .then( json=>{

            if ( $( '#line' ).data('first-time') != 'no' ) {
                line.innerHTML='';
                $( '#line' ).data('first-time', 'no');
            }

            Object.keys( json ).forEach( key=>{
                let obj=json[ key ];
                line.append( new Option( obj.line, obj.line ) );
            })
        })
};