0

Is anyone able to tell me please why clicking on this in an HTML page

<a onclick="addRow(); return false;" href="#">Add Row</a>

causes addRow to be called, but this

<input id="addRow" type="button" value="Add Row" onclick="addRow(); return false;" />

does not?

(I want a button which calls addRow.)

7
  • post the addRow() function Commented Jul 1, 2015 at 10:32
  • Hmm, easier said than done. If I add it I can't submit the edit - StackOverflow complains that my post is mostly code and I need to add some more details. Not really sure what it wants. It there a specific thing you are looking for? The function DOES work when called in the first way. Commented Jul 1, 2015 at 10:36
  • 1
    Seems to work fine. Although I'm not sure that an href on an <input> is valid, I would remove it. Also is that input item in a form? Commented Jul 1, 2015 at 10:37
  • Sorry, the href was a hangover from something I was trying. Removed. Yes the input item is in a form. Commented Jul 1, 2015 at 10:42
  • something to do with id? which input has but <a> doesn't? between any errors in the console? Commented Jul 1, 2015 at 10:45

2 Answers 2

2

Other that adding the JavaScript as a onclick inline with the HTML add it as an event listener in JavaScript:

document.getElementById("addRow").addEventListener("click", addRow, false);

The problem is coming from the id's name addRow vs the function call addRow(), since some browsers will interpret id's as global variable names. This causes an issue with the function call inline HTML. Simply changing the id or function name also works, for example changing the id to id="add_row":

<input id="add_row" type="button" value="Add Row" onclick="addRow(); return false;" />
Sign up to request clarification or add additional context in comments.

Comments

1

you can add listener on button like this, here is the demo code...

<button id="btn">Click me</button>

var button = document.getElementById('btn');
button.addEventListener("click", function(){
   addRow();
});
function addRow() {
   alert("working");
}

FIDDLE DEMO

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.