Jump to content

Input Onlick


astralaaron

Recommended Posts

is it possible to write a javascript function inside of the onclick tag? example:<input type="button" value="send" onclick="function sendform() { if(!confirm("Are you sure you want to send?")){ return false; } if(http8.readyState == 0 || http8.readyState == 4){ http8.open("GET",<?php echo($sendURL); ?>,true); http8.onreadystatechange = formresult; http8.send(null); } } function formresult(){ if(http8.readyState == 4){ return true; } } " />

Link to comment
Share on other sites

Yes and no. No, in the sense that you cannot assign a function to element.onclick in the the tag the same way you can in a script.The reason is subtle. A click handler assignment in a script literally assigns a function to the handler. At that point, the handler becomes a reference to a function object.A click handler in a tag assigns a string to the handler; the handler becomes a reference to a string object. Even if a function is defined in the string, it doesn't really get assigned to the handler.But yes, there is a way around the difference, though I don't see the utility. It is to create a named function and then call it. Like this:

<button onclick="function bark () {	alert ('Woof');};bark();">click</button>

The down side to this is that scope gets all messed up, and the convenience of the 'this' keyword gets mangled. To recreate it, we have to bend over backwards. As you can see, the following is a lot of code to do a really simple thing.

<button onclick="var el = this;function bark () {	alert (el.innerHTML);};bark();">click</button>

BUT THE MOST IMPORTANT thing is this. Don't do it. The whole direction of modern HTML is to separate content from presentation and also from behavior. Handlers (even little ones) should be assigned in a script, not in a tag. The best HTML is easy to read and maintain because it is clean. A bunch of Javascript just clutters things up.

Link to comment
Share on other sites

You can also do something like this. I think this will work, anyway.<input type="button" value="send" onclick="(function() {return function() {if(!confirm("Are you sure you want to send?")){return false;} if(http8.readyState == 0 || http8.readyState == 4){http8.open("GET",<?php echo($sendURL); ?>,true);http8.onreadystatechange = formresult;http8.send(null);}}function formresult(){if(http8.readyState == 4){return true;}};})(); " />Of course, like Dad said, *why* you would want to do that is beyond me.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...