I'm trying to grab a dynamically generated ID from a form input, then wait for the user to submit it and process the submit only if the ID contains the string "comment". Currently, I can get the ID but the submit default action doesn't get prevented and a regular POST action occurs instead of the ajax. After days of trying to figure this out on my own, I'm feeling defeated... Any help would be greatly appreciated.
$(document).ready(function() {
var fullID;
$(".post-new-comment-input").click(function(){
fullID = $(this).attr('id');
});
$(this).submit(function(e)
{
if(fullID.indexOf("comment") > -1) <?php // execute only if the fullID contains "comment" ?>
{
e.preventDefault();
var value = $('#'+fullID).val();
var justID = fullID.substring(8); <?php // truncate first 8 chars, the 'comment-') ?>
$.ajax({
type: "POST",
url: "actions",
data: { 'comment-pid': justID, 'comment-uid': <?php echo get_current_user_id(); ?>, comment: value },
dataType: 'json',
success : function(response)
{
$('#post-discussion-'+justID).html(response[0]);
$('#comments-count-'+justID).html(response[1]);
}
});
$('#'+fullID).val(null); <?php // clear the input field after returning post result ?>
}
});
});
Here's the form:
<div class="comment-form">
<form>
<input type="text" id="comment-<?php echo $post_id; ?>" class="post-new-comment-input" placeholder="Write your comment...">
<input type="submit" class="hide">
</form>
</div>
(Sorry if the formatting is messed up, I'm not used to how SO's post formatting)
<input type="submit">