0

My HTML:

<table id="laboral">
    <tr>
        <td><input type="text" name="start"/></td>
        <td><input type="text" name="end"/></td>
        <td><textarea name="desc"></textarea></td>
        <td><button type="button" onclick="saveRow(this);"> + </button></td>
    </tr>
</table>

When I press the + button I create a new row exactly as the first one, but the onclick event doesn't work:

Here's the code for saving the values and create the 2 inputs and the textarea:

var button = document.createElement("button");
button.type = "button";
button.setAttribute("onclick", "saveRow(this);")
button.innerHTML = "+";
var btn = tr.insertCell(3);
btn.appendChild(button);    

If I examine the result with Firefox I can see that the first button and the new generated have the same code. But the generated doesn't work.

12
  • 1
    Can you please demo it in jsfiddle or something similar? Commented Nov 10, 2013 at 11:16
  • 3
    Browsers have been compatible? What? First of all that's not true, second, JQuery is not only for incompatibilities, but especially for making DOM manipulation easier. Commented Nov 10, 2013 at 11:22
  • 2
    What is this, the "how many false premises can we fit into a single sentence" game? Commented Nov 10, 2013 at 11:23
  • 2
    @AntP He is just trolling, or clearly doesn't work in an environment which produces consumer-facing websites. His original point is correct though, no need for jQuery here. Commented Nov 10, 2013 at 11:23
  • 2
    Not the place for this. I didn't say that Vanilla JS isn't possible it's just that for public-facing websites it's not worthwhile. e.g. I can write a computer program in Assembly. Does that make C, C++, C# obsolete? Definitely not. Does it make life easier? Sure does. No need for elitism here, just useful answers. Commented Nov 10, 2013 at 11:30

1 Answer 1

1

Rather than define an event handler for all the buttons you may add, it may be more efficient to defer it to the table. In this case, you'd do this:

// this script should be placed after the table on the page, or deferred in some way
document.getElementById('laboral').onclick = function(e) {
    e = e || window.event;
    var elem = e.srcElement || e.target;
    if( !elem.tagName) elem = elem.parentNode;
    if( elem.tagName == "BUTTON") {
        var tr = elem;
        // find the row that contains the button
        while(tr.tagName != "TR") tr = tr.parentNode;
        tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
    }
};

Done ^_^

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.