0

I keep getting the error "Uncaught TypeError: Cannot read property 'add' of null", which happens on the line select.add("HI!", 0);. I thought it was because of a name mismatch, which is why the list exists, but that did not solve the problem. Any guidance would be awesome!

<script type="text/javascript">
        for(i = 0; i < 10; i++){
            var names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
            //window.alert(names[i])
            document.write('<tr>');
            document.write('<td>');
            document.write('<select id=names[i]></select>');        
            var select = document.getElementById(names[i]);
            select.add("HI!", 0);           
            document.write('</td>');
            document.write('</tr>');
        }
    </script>

Thank you

Drew
  • 167
  • 1
  • 4
  • 13

2 Answers2

2

You can't just add text to a select, you need to make an option element and then add it. Try this:

<script type="text/javascript">
    for(i = 0; i < 10; i++){
        var names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        //window.alert(names[i])
        document.write('<tr>');
        document.write('<td>');
        document.write('<select id=' + names[i] + '></select>');        
        var select = document.getElementById(names[i]);
        var option = document.createElement('option');
        option.text = 'Hi';
        select.add(option, i)
        document.write('</td>');
        document.write('</tr>');
    }
</script>
leitning
  • 297
  • 1
  • 2
  • 7
1

Your document.write('<select id=names[i]></select>'); will write that exact string, not the value from the array as you intended. You could instead try: document.write('<select id=' + names[i] + '></select>');

As isherwood and your error noted, you must pass an option or optiongroup element to the add method for it to work.

Community
  • 1
  • 1
yts
  • 1,755
  • 12
  • 22
  • I added the line in and got the error `Uncaught TypeError: Failed to execute 'add' on 'HTMLSelectElement': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)` Is this because it is not creating an actual select item? – Drew Apr 14 '15 at 19:35
  • The answer is correct, but there's more to it. You also need to properly construction the option element. http://jsbin.com/xaxulebuso/1/edit?js,output – isherwood Apr 14 '15 at 19:42
  • @Drew what isherwood said. You weren't passing the correct arguments to the `add` method, as the error stated. – yts Apr 14 '15 at 19:45