I am dynamically creating forms from a JSON object that I fetch with a getJSON. If there is a better way of building forms in this manner, please let me know. I used this example to understand how to rebind submit button: http://stackoverflow.com/questions/2754961/rebind-dymanically-created-forms-after-jquery-ajax-response**
What I need to know is how to grab the class of the input submit button I have clicked. There's an "Approve" and "Deny" button and depending on which one is clicked will be sent to the server in a POST so I know what to do with the form data being POST'ed on the server side.
Here's the code:
<script type="text/javascript">
$().ready(function(){
jQuery("form[id^='message-']").live('submit', function(){
var id = parseInt(this.id.replace("message-", ""));
// this is not the value of the class attribute from submit button clicked.
var action = this.attr('class');
alert(action);
return false;
jQuery.ajax({
type: "POST",
url: "/path/to/ajaxhandler.php",
data: {"action": action, "id": id},
success: function(response) {
}
});
/*
generate form
*/
$.fn.getAllUnapprovedMessages = function () {
$.getJSON("/messages.php?a=getAllUnapproved, function(data){
var i=0;
$("div#messages").empty();
while(i<data.length) {
$('div#messages').append(
'<div id="msg-'+data[i].id+'" style="border: 1px coral solid; margin: 5px 5px 5px 5px;">'+
'<form id="message-'+data[i].id+'" name="form-'+data[i].id+'" action="/path/to/ajaxhandler.php" >'+
'From: '+data[i].u_from+' ----> To: '+data[i].u_to+'<br />'+
'Subject: <br /><input name="subject" type="text" value="'+data[i].subject+'" /> <br /><br />'+
'Message: <br /><textarea rows="10" cols="60">'+data[i].text+'</textarea><br />'+
'<input class="formApprove" type="submit" id="approve-'+data[i].id+'" value="Approve" /> or '+
'<input class="formDeny" type="submit" id="deny-'+data[i].id+'" value="Deny" />'+
'</form></div>');
i++;
}
});
}
}
</script>
Here is what I need to change to be correct:
// this is not the value of the class attribute from submit button clicked.
var action = this.attr('class');
alert(action);
So I can get the class attribute from the button that was clicked.
UPDATE (8.27.2010) - Here's what I did for anyone who stumbles across this and needs an answer:
For the serializeObject() function, see this post: http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery
$(".formApprove").live('click', function() {
var fid = this.id.replace(/approve-/i, "");
var formObject = $('form#message-'+fid).serializeObject();
$.post('/path/to/ajaxhandler.php', {
a: 'setApproved',
id: fid,
subject: formObject.subject,
message: formObject.message
}, function(res) {
if(res.result == 0) {
alert ('done');
} else {
alert ('Error');
},"json");
return false;
});