Reputation: 1258
I am obviously doing something dumb, I can't quite see what's wrong. Whenever I click the "Send" button, the click event fails to fire.
function CreateNewMessage()
{
var receiver = $("#receiver").value;
var msg_body = ("#msg_body").value;
$("#submit").click(function(event) {
alert("it works!");
$.post("new/", {"receiver" : receiver, "msg_body" : msg_body});
});
}
(function() {
$(document).ready(function() {
CreateNewMessage();
});
})();
and the HTML button
<input id="submit" value="Send" type="submit">
Who can spot my error?
EDIT:
So here is what my code looks like now after taking everyone's suggestions into consideration.
function CreateNewMessage()
{
$("#submit").click(function(event) {
var receiver = $("#receiver").val();
var msg_body = $("#msg_body").val();
alert("it works!");
$.post("message/new/", {"receiver" : receiver, "msg_body" : msg_body});
});
}
$(document).ready(function() {
CreateNewMessage();
});
It still is not sending a request properly, and the console is not logging an errors. I tried using the submit event as opposed to the click event in the code above but got the same results.
EDIT 2 So the code is working on jsFiddle but not in my browser. I am really confused
EDIT 3: Maybe this has something to do with it... Note that the submit button does not exist when the page is initially loaded. It is generated when a specific javascript event fires.
Upvotes: 0
Views: 3099
Reputation: 155055
You're missing the $()
function for #msg_body
, it should be like so:
var receiver = $("#receiver")[0].value;
var msg_body = $("#msg_body")[0].value;
Also, you don't need to wrap the ready
in a function, you can call it directly in your script; you can also set your CreateNewMessage function as the handler directly, like so:
$(document).ready( CreateNewMessage );
Upvotes: 3
Reputation: 6844
Value with jQuery is .val(). Also, why not listen to the submit event? If you don't want the post to go through, simply make it return false.
Upvotes: 1
Reputation: 696
Try this:
function CreateNewMessage()
{
var receiver = $("#receiver").value;
var msg_body = $("#msg_body").value;
alert("it works!");
$.post("new/", {"receiver" : receiver, "msg_body" : msg_body});
}
$(function(){
$("#submit").click(function() {
CreateNewMessage();
});
});
Upvotes: 0
Reputation: 17522
You missed the $ before ("#msg_body") so your script will crash there.
function CreateNewMessage()
{
var receiver = $("#receiver").value;
var msg_body = $("#msg_body").value;
$("#submit").click(function(event) {
alert("it works!");
$.post("new/", {"receiver" : receiver, "msg_body" : msg_body});
});
}
(function() {
$(document).ready(function() {
CreateNewMessage();
});
})();
Upvotes: 0