0

Trying to focus on the first object of a select list in a for loop. The loop populates the list with the same .txt to make multiple of the same select box

<script type="text/javascript">
for(i = 0; i < 10; i++){
    var names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    document.write('<tr>');
    document.write('<td>');
    document.write('Enter name '+ names[i]);
    document.write('</td>');
    document.write('<td>');
    document.write('<select id=' + names[i] + '></select>');     
    var textFile = "/names.txt";       
    jQuery.get(textFile, function(textFileData) {
        var EachName= textFileData.split("\n");
        for (q = 0; q < 10; q++) {
            var select = document.getElementById(names[q]);
            for (var j = 0, len = EachName.length; j < len; j++) {
                var option = document.createElement('option');
                   option.text = option.value = EachName[j];
                select.add(option, 0);
            };
        };
    });   
    $(document).ready(function(){
        $("select:first").focus();
    });
    document.write('</td>');
    document.write('</tr>');
};
</script>

I am trying to focus on the first selection object in the list, but no matter where I seem to put the JavaScript, it would not focus. I don’t know what I’m doing wrong. Any ideas?

Yasen Zhelev
  • 4,045
  • 3
  • 31
  • 56
Drew
  • 197
  • 2
  • 6
  • 13

1 Answers1

0

Try something like this:

$(document).ready(function(){
    for(i = 0; i < 10; i++){
        var names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        document.write('<tr>');
        document.write('<td>');
        document.write('Enter name '+ names[i]);
        document.write('</td>');
        document.write('<td>');
        document.write('<select id=' + names[i] + '></select>');     
        var textFile = "/names.txt";      

        jQuery.get(textFile, function(textFileData) { 
            var EachName= textFileData.split("\n");
            for (q = 0; q < 10; q++) { 
                var select = document.getElementById(names[q]);
                for (var j = 0, len = EachName.length; j < len; j++) {
                    var option = document.createElement('option');
                    option.text = option.value = EachName[j];
                    select.add(option, 0);
                }
            }
        });   
        document.write('</td>');
        document.write('</tr>');
    }
    document.getElementById("1").selectedIndex = 0;
    document.getElementById("1").focus();
});

Put your logic for populating the selects in the document.ready function...

brso05
  • 13,142
  • 2
  • 21
  • 40