arrowinfedex arrowinfedex - 3 months ago 9
Javascript Question

When loading an array of photos, how can I make a unique comment button function for each imageID?


  1. Page loads with reference to commentIMage.js, and comment.php

  2. User enters comment and clicks button, references from commentImage.js

  3. comentImage.js ($comment).click(function{..}) doesn't load



html

<textarea required=required name ="comment" id="comment"></textarea><br/>
<input type="hidden" id="image" name ="image" value="<?php echo $images[$i]['imageID']?>" />
<input type=button id=postComment value="Post Comment">


commentImage.js
$(document).ready(function(){

$('#postComment').click(function(){
$.ajax({
type:'post',
url:'commentImage.php',
data:{newComment:$('#comment').val(), postID:postID},
success:function(data){
var data = JSON.parse(data);
var comment = makeComment(data['user'], $('#comment').val(), data['date']);
$('#commentsBock').prepend(comment);
$('#comment').val('');
}
})
})
})

function makeComment(user, comment, date){
var comment = '<div><div>'+user+'</div><div>'+comment+'</div><div>'+date+'</div><div>';
return comment;
}
function getComments(){

}


commentImage.php

<?php
session_start();
echo $_POST['comment'];
echo $_POST['image'];
include_once('mysql.php');
...
?>

Answer

#comment is a unique ID. If you use it more than one time in your HTML, don't wait for it to work properly, it won't !

Just use your PostID like id="comment_"+PostID to create unique identifiers. And use $("input[id^='comment_']") to select all IDs which id start with comment_ (that's what ^= does)

JS Fiddle