Reputation: 372
Here is my code:
$(".cbtn").click(function(e) {
alert("here");
var id = $(this).attr('id');
var comment = $('input[id$=id]').val();
alert("hay" + id);
alert(comment);
$.post("comments.php", {
id: id,
comment: comment
})
});
});
The id
of cbtn
and the text field is created dynamically like this:
<input type="text" class="enter_comment value="comments" id="comm<?php echo $row['p_id'];?>"/>
<input type="button" value="enter" class="cbtn" id="<?php echo $row['p_id'];>">
When cbtn
is clicked, I want to get the id
of text field that ends with the same id as cbtn
. But it is returning undefined
instead.
Upvotes: 0
Views: 829
Reputation: 337714
You need to concatenate the id
variable in the selector, like this:
$(".cbtn").click(function(e) {
var id = this.id;
var comment = $('input[id$=' + id + ']').val();
$.post("comments.php", {
id: id,
comment: comment
})
});
Alternatively, as the id
of the text field is the same as the checkbox, but with comm
prepended, you could select it by id
directly, which would be quicker:
var comment = $('#comm' + id).val();
Or, if the text field is always the element preceding the checkbox, you could negate the need to select by id
completely and use the prev()
method:
$(".cbtn").click(function(e) {
$.post("comments.php", {
id: this.id,
comment: $(this).prev().val()
})
});
Upvotes: 5