1

Good afternoon everybody - I have a (probably) simplistic question that I can't seem to find the answer to after searching fairly thoroughly. The error that I'm getting in chrome is "Uncaught TypeError: Cannot read property 'value' of null." on line 120 (copied below):

mercedes_txt = mercedes_txt + "<tr><td><button id=\"Mercedes Add Value\"
    onclick=\"addAttribute('Merceds-Benz', " + mercedes_counter + ", '" +
    document.getElementById('Mercedes-Benz Text').value + "')\">Add</button></td><td>
    <input type=\"text\" name=\"Mercedes-Benz Text\" id=\"Mercedes-Benz Text\" />
    </td></tr></table>";

I tried to divide the code up on multiple lines for readability purposes. If I take out "onclick" the code executes properly. Also, if I replace

'" + document.getElementById ('Mercedes-Benz Text').value + "'

with 'someValue', the code executes properly. So the problem must be that I'm requesting the value from an object that is dynamically created (it doesn't exist yet, but will once the code is applied in an innerHTML call). Sorry that I'm a novice but I appreciate everyone's help.

Michael Koehler
  • 13
  • 1
  • 1
  • 3
  • 3
    I don't think id attributes can contain spaces like that. So you're probably failing to get your element because of the invalid id. Also, you can't get elements that don't exist yet! – bfavaretto Mar 05 '13 at 19:29
  • 1
    @bfavaretto correct. http://www.w3.org/TR/html5/dom.html#the-id-attribute – Matt Ball Mar 05 '13 at 19:32

1 Answers1

2

I see two errors:

  1. Trying to use an invalid id for your element. See What are valid values for the id attribute in HTML? for the id naming rules.

  2. You're trying to get the value of an element that you didn't add to the DOM yet.

I suggest getting rid of that inline onclick handler, and add by code. Something like this:

var addValueButton = document.getElementById('MercedesAddValue');
addValueButton.addEventListener('click', function(e) {
   // get live form values here by traversing the DOM
   // you may want to use jQuery...
});
Community
  • 1
  • 1
bfavaretto
  • 69,385
  • 15
  • 102
  • 145
  • Thanks, you're right, I was using an invalid ID for my element. I've changed that now but I'm still getting the same error because I haven't added the element to the DOM yet - how do I go about fixing that? Thanks! – Michael Koehler Mar 05 '13 at 19:34