So I have this code that should listen for a click on #button but it won't work, and is driving me crazy!
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$('#button').click(function() {
alert('OK!');
});
</script>
and the HTML:
<input id="button" type="button" value="OK" />
This is strange. Any help is welcome!
jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn't present when the page is ready.
If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.
The JavaScript addEventListener() method allows you to set up functions to be called when a specified event happens, such as when a user clicks a button.
To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.
Write your code inside document.ready function
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#button').click(function() {
alert('OK!');
});
});
</script>
OR
<script type="text/javascript">
function on_click() {
alert("OK !!");
}
$(document).ready(function() {
$("#button").click(on_click);
});
</script>
hope you get some idea from this
Here's what the code should look like:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript">
// Now that jquery is include, place the code to wire up the button here
$(function(){
// Once the document.onload event fires, attach the click
// event handler for the button
$('#button').click(function() {
alert('OK!');
});
});
</script>
<input id="button" type="button" value="OK" />
Here's the jquery documentation that relates to this: http://docs.jquery.com/How_jQuery_Works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With