Ved
Ved

Reputation: 8777

JavaScript RunTime Error : appendChild() - Unexpected call to method or property in IE8

I am getting runtime JS error like : "Unexpected call to method or property". Here is the code :

    var comboInput = document.getElementById("Combo");
    var option1 = document.createElement("option");
    option1.value = "-1";
    option1.innerHTML = "--Select--";
    comboInput.appendChild(option1); //At this line debugger breaks and
                                     // throws the above error

I gone through some of similar questions on SO about this issue but still not getting the solution.

Please help.. Thanks in adv...

Upvotes: 0

Views: 1240

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

You can't append children to <input> elements.

<option> elements can only be children of <select> elements, where <select> elements are html's version of a drop-down list (or a multiselect list depending on the attributes you give it).

Try changing your html so that your "Combo" element is like this:

<select id="Combo"></select>

and then your code should work.

Note though that you can set options directly in the html markup, e.g.,

<select id="Combo">
    <option value="-1">--Select--</option>
    <option value="1">Green</option>
    <option value="2">Purple</option>
</select>

(And having put options in your html you can add additional options and/or remove options via JS.)

Upvotes: 1

jfriend00
jfriend00

Reputation: 708136

You need to check on the value of comboInput (output its value with console.log() or in an alert() to see what it's set to).

It likely has a value of null because your code didn't find an existing object with id="Combo". This can be because:

  1. Such an object doesn't exist in your page
  2. You didn't get the id exactly right
  3. You're running this code before the page has loaded so the object hasn't yet been loaded/created.

If you include the entire page context (all HTML and all JS or a link to a live page), we could tell you more specifically what steps should be taken to correct the issue.

Upvotes: 1

Related Questions