I have following code:
<div id="comments" class="clearfix">
<div class="conversation box_round_s box_shadow clearfix mtm">
<div class="conversation box_round_s box_shadow clearfix mtm">
<input class="conv_tracker" type="hidden" value="4695f1db2d">
<div class="conv-header">2</div>
<div class="comment pts plm prs pbs">
<div class="comment plxl pts plm prs pbs">
<div class="replybox pvs clearfix">
<textarea class="comment_txt_r fses fft"></textarea>
</div>
</div>
<div class="conversation box_round_s box_shadow clearfix mtm">
<div class="conversation box_round_s box_shadow clearfix mtm">
</div>
and I’m trying to read the value of input with class conv_tracker (4th line in code with value=”4695f1db2d”). I want to read this value. I’m reading it when someone presses enter in textarea. there are multiple text areas on page. I’m using following jquery:
the code does enter inside the if, but shows undefined.
$(".comment_txt_r").keydown(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
var ctext = $(this).val();
var relid = $(this).closest('.conversation').children('input.conv_tracker').val();
alert(relid);
}
});
can anybody please tell me what I’m doing wrong?
Use
$('#conv_tracker').val(). The ID must be unique within the page, so there is no reason to traverse up and down the DOM viaclosestandchildren, and then select by ID. Just select by ID.It’s very likely that if your current code isn’t working, the ID is not unique within the page, and it’s being stripped off the later elements with duplicate IDs preventing your code from selecting the element. If this is the case, you need to use a class or some other attribute for the repeated elements.
As an unrelated suggestion, try using
dataattributes and attaching the value directly to the element you’re binding the events to, rather than dumping random, uncoupled, semantically meaningless elements into the DOM.Your text area gets a
data-conv-trackerattribute:And your code is simplified drastically with no additional selection/DOM traversal: