Get jQuery function to trigger on HTML Button OnClick
I have the following HTML/JQuery:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login</title>
<script src="jQuery.js"></script>
<script>
$(document).ready(function(){
$(function(){
$("#sb").click(function(e){
e.preventDefault();
getmessage = "Yes";
getmessage = encodeURIComponent(getmessage);//url encodes data
$.ajax({
type: "POST",
url: "get_login.php",
data: {'getmessage': getmessage},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
});
});
});
});
</script>
</head>
<body>
<h1>Login</h1>
<p>Please enter your e-mail and password</p>
<form name = "loginform" action = "http://dev.speechlink.co.uk/David/get_login.php" method = "post">
<p>E-mail<input name = "username" type="text" size="25"/><label id ="emailStatus"></label></开发者_开发问答p>
<p>Password<input name = "password" type="text" size="25"/><label id ="passwordStatus"></label></p>
<p><input type="hidden" name="usertype" value = "SupportStaff" /></p>
<p>><input type ="button" id = "sb"value="Create Account"/></p>
</form>
<div id = "message_ajax"></div>
</body>
</html>
I cannot get the event handler (within the jQuery) to trigger upon the user pressing the 'Create Account' button...
I see three issues off-the-bat:
You're calling
ready
twice (when you pass a function into$()
, it's just like passing a function into$(document).ready()
). This is largely harmless, but completely unnecessary.Your attribute for the
id
on the button is rammed up against the next; it's possible the browser is ignoring it:<input type ="button" id = "sb"value="Create Account"/> <!-- ^^^^^^^^^ -->
(It's fine to have spaces around the
=
if you want, but having the"sb"
rammed up intovalue
may not work.)(Possibly off-topic, possibly not): You seem (from the quoted code) to be falling prey to The Horror of Implicit Globals. You should probably declare your
getmessage
variable.
So:
<script>
$(document).ready(function(){
// Removed the unnecessary `$(function() { ...` here and the matching closing bits at the end
$("#sb").click(function(e){
e.preventDefault();
var getmessage = "Yes"; // <== Added `var`
getmessage = encodeURIComponent(getmessage);//url encodes data
$.ajax({
type: "POST",
url: "get_login.php",
data: {'getmessage': getmessage},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
});
});
});
</script>
and
<input type="button" id="sb" value="Create Account"/>
You html is not good:
<p>><input type ="button" id = "sb" value="Create Account"/></p>
should be
<p><input type ="button" id="sb" value="Create Account"/></p>
精彩评论