I am working on a project,i have a div in which i have multiple divs, each div have unique ID(from DB) and each div contains a textbox for adding comment
like below
<div id="maindiv">
<div id="@item.resid">
<p>Content1</p>
<input type="text" class="txtarea" resourceid="@item.resid"/>
</div>
<div id="@item.resid">
<p>Content2</p>
<input type="text" class="txtarea" resourceid="@item.resid"/>
</div>
<div id="@item.resid">
<p>Content3</p>
<input type="text" class="txtarea" resourceid="@item.resid"/>
</div>
<div id="@item.resid">
<p>Content4</p>
<input type="text" class="txtarea" resourceid="@item.resid"/>
</div>
.
.
.
.
i am adding comment by keypress event of textbox, the problem i am having is that when i add comment on content at downside, then after adding the focus comes on top.
I have tried focusing on textbox and even on div but not worked 🙁
below is my code of adding comment
$(".txtarea").keypress(function (e) {
if (e.keyCode == 13) {
if ($(this).val().trim() != "") {
var commentText = $(this).val();
var resourceid = $(this).attr('resourceid');
var divId = "." + resourceid;
$.ajax({
url: ResourceAjaxUrl.AddNewCommentOnResources,
type: "POST",
data: JSON.stringify({ resourceID: resourceid, commentText: commentText }),
dataType: "html",
contentType: "application/json; charset-utf-8",
success: function (Result) {
$('#maindiv').html(Result);
$('#maindiv div#' + divId.split('.')[1]).focus();
$('#maindiv div#' + divId.split('.')[1]).find(".txtarea").focus();
},
error: function (msg) {
alert("Unable to save comment in");
}
});
}
else {
$(this).val('');
$(this).focus();
}
}
});
i’ve seen focus() line on developer tool, its working fine but still not focusing, i want that if i add comment on downside(or last) comment, the focus will stay on that instead of going on top
You can’t set a focus on a div. It is for form elements (inputs, textareas, buttons etc.) only.
Looks like your problem is that you have wrong ID in selector when trying to find a
.txtarea:replaced with
Besides, once you have a unique ID, you do not need to write
$('#maindiv div#' + divId.split('.')[1]). This is enough:$('#' + divId.split('.')[1])(id must be unique for a whole page anyway, so no need to specify that it is adivlocated inside#maindiv)