1

I have the following html:

    <input type="text" id="theInput" />

<input id="clickMe" type="button" value="Search" onclick="testFunction(document.getElementById('theInput').value)" /><br>

I am trying to trigger this:

function testFunction(data)
{
    alert(data);
}

I also tried an alternative, using:

document.getElementById("clickMe").onclick = testFunction(document.getElementById("theInput").value);

Sadly, neither of these methods seem to get the function to trigger. I'm sure I am missing something simple, could anyone point it out, please?

2
  • ur missing value attr in input Commented Jul 22, 2013 at 2:09
  • 2nd option is wrong... onclick = handler;.... the handler has to be a function reference whereas you are setting the returned value of testFunction that will be undefined in your case. use onclick=function(){/*testFunction execution code*/}; Commented Jul 22, 2013 at 2:30

2 Answers 2

2

I have test and found that your code is OK, you can see the demo here. However, I think it not work in your page because of the way you include your javascript functions. You have better to put all scripts in the head tag of the page.

If you use some framework, make sure your functions and bindings are executed when all javascript loaded.

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

1 Comment

It works for me, also, once I abstract it. In the larger code I am trying to work with, it's not firing. It's infuriating. But nice to know the logic was right.
0

Instead of assigning onclick, which only allows you to add a single click handler to the element, you should use addEventListener which allows you to register multiple listeners. See below:

document.getElementById('clickMe').addEventListener('click', function () {
    alert(document.getElementById('theInput').value);
});

JSFiddle demo here

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.