We are trying to dynamically add tasks using the below javascript on click event. I ran into this problem with my code. I want to push the created objects into an array and then display in a bootstrap card.
let button = document.getElementById('clickMe');
button.addEventListener('click', addCard({
'name': 'juice'
}
))
function addCard(card) {
const cardBody = `<div class="card" id="newCard">
<h5 class="card-header bg bg-warning">Task Card <span id="time" style = "padding-top:5px;"></span></h5>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text"><strong>${card.name}<br>Assigned to<br>Due date<br>Status<br>Description</strong></p>
</div>
<div class="card-footer">
Edit
Delete
</div>
</div> `;
let cardList = document.getElementById('cardList')
cardList.innerHTML += cardBody;
}
<form>
<input type="text" id="nameF">
<span id="msgErr"></span>
<br>
<br>
<input type="text" id="nameL">
<span id="msgErr"></span>
<br>
<br>
<button type="button" id="clickMe">Validate</button>
<span id="currentTime"></span>
</form>
<div class="container card-columns" id="cardList">
<div class="card" id="newCard">
<h5 class="card-header bg bg-warning">Task Card <span id="time" style="padding-top:5px;"></span></h5>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text"><strong>Name<br>Assigned to<br>Due date<br>Status<br>Description</strong></p>
</div>
<div class="card-footer">
Edit
Delete
</div>
</div>
I'd probably tweak your codes a bit become like this, to make it more dynamic and easier.
The problem in your snippet is, it failed to call addCard function when you click the <button>.
function addCard() {
const card = {
name: document.getElementById('nameF').value + ' ' + document.getElementById('nameL').value
};
const cardBody = `
<div class="card" id="newCard">
<h5 class="card-header bg bg-warning">Task Card <span id="time" style = "padding-top:5px;"></span></h5>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text">
<strong>
${card.name}
<br>
Assigned to
<br>
Due date
<br>
Status
<br>
Description
</strong>
</p>
</div>
<div class="card-footer">
Edit
Delete
</div>
</div> `;
const cardList = document.getElementById('cardList');
cardList.innerHTML += cardBody;
}
<form>
<input type="text" id="nameF">
<span id="msgErr"></span>
<br>
<br>
<input type="text" id="nameL">
<span id="msgErr"></span>
<br>
<br>
<button type="button" id="clickMe" onclick="addCard()">Validate</button>
<span id="currentTime"></span>
</form>
<div class="container card-columns" id="cardList">
<div class="card" id="newCard">
<h5 class="card-header bg bg-warning">
Task Card <span id="time" style="padding-top:5px;"></span>
</h5>
<div class="card-body">
<h5 class="card-title"></h5>
<p class="card-text">
<strong>
Name
<br>
Assigned to
<br>
Due date
<br>
Status
<br>
Description
</strong>
</p>
</div>
<div class="card-footer">
Edit
Delete
</div>
</div>
</div>
Related
I want to update the comments of a post. Let's say the user has 2 comments, when he clicks edit I want to close the window of the other comment. In short, how can I keep one as "textarea" and the other as "span"?
$(document).on('click','.update-comment',function(e){
$('.active').removeClass('active');
let obj = $(this).closest('.comments');
let text = obj.find('.comment-text').attr('data-text');
obj.find('.ms-3').addClass('active');
if($('.ms-3').hasClass('active')){
$(obj.find('.comment-text')).replaceWith('<textarea id="updateComment">'+text+'</textarea>');
}else {
$(obj.find('.comment-text')).replaceWith('<span class="comment-text" data-text='+text+'>'+text+'</span>');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex py-2 comments" data-id="1">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/50" alt="..."/>
</div>
<div class="ms-3">
<div class="fw-bold">Name-1
<button type="submit" class="update-comment" data-id="1">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 1" data-id="1">Comment Example - 1</span>
</div>
</div>
<hr>
<div class="d-flex py-2 comments" data-id="2">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/100" alt="..."/>
</div>
<div class="ms-3">
<div class="fw-bold">Name-2
<button type="submit" class="update-comment" data-id="2">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 2" data-id="2">Comment Example - 2</span>
</div>
</div>
<hr>
Not trivial
I changed the button to type=button
I then removed the duplicate IDs and instead gave both span and textarea the class of comment-text
Then I changed the data-attr to just the .text() OR .val() depending on the element being a textarea or a span
I also cached several objects
$(document).on('click', '.update-comment', function(e) {
$allMS3 = $('.ms-3').removeClass('active');
let $thisMS3 = $(this).closest('.ms-3')
.addClass('active');
$allMS3.each(function() {
const $commentText = $(this).find('.comment-text')
let text = $commentText.is("span") ? $commentText.text() : $commentText.val();
if ($(this).hasClass('active')) {
$commentText.replaceWith('<textarea class="comment-text">' + text + '</textarea>');
} else {
$commentText.replaceWith('<span class="comment-text">' + text + '</span>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex py-2 comments" data-id="1">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/50" alt="..." />
</div>
<div class="ms-3">
<div class="fw-bold">Name-1
<button type="button" class="update-comment" data-id="1">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 1" data-id="1">Comment Example - 1</span>
</div>
</div>
<hr>
<div class="d-flex py-2 comments" data-id="2">
<div class="flex-shrink-0">
<img src="https://via.placeholder.com/100" alt="..." />
</div>
<div class="ms-3">
<div class="fw-bold">Name-2
<button type="button" class="update-comment" data-id="2">Edit</button>
</div>
<span class="comment-text" data-text="Comment Example - 2" data-id="2">Comment Example - 2</span>
</div>
</div>
<hr>
enter image description here
I am supposed to have three cards on large screens, 2 in tablets, 1 in mobile and all without hard coded html. Only through javascript. However, when I try to add three cards in the same row, it takes the same movie for the entire row and then the next one for the second row and so on..
Also the button only works for the first card...
There must be smth wrong in my loop..
This is my code so far:
var parsedMovies = JSON.parse(movies);
for (let i = 0; i < parsedMovies.length; i++) {
document.getElementById("cards").innerHTML += `
<div class="card-group">
<div class="card mb-3 bg-dark text-light" style="max-width: 540px;">
<div class="row g-0 ">
<div class="col-md-4 ">
<img src="${parsedMovies[i].image}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">${parsedMovies[i].title}</h5>
<p class="card-text">${parsedMovies[i].plot}</p>
<p class="card-text"><small class="text-muted"> Year: ${parsedMovies[i].year} <br> Director: ${parsedMovies[i].director} <br> Actors: ${parsedMovies[i].actors}</small>
<div class="voting">
<button id="likebtn">
<i>👍</i>
</button>
<input type="number" id="input1" value="${parsedMovies[i].likes}">
<button id="dislikebtn">
<i>👎</i>
</button>
<input type="number" id="input2" value="${parsedMovies[i].dislikes}">
</div>
</p>
</div>
</div>
</div>
</div>
<div class="card mb-3 bg-dark text-light" style="max-width: 540px;">
<div class="row g-0 ">
<div class="col-md-4 ">
<img src="${parsedMovies[i].image}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">${parsedMovies[i].title}</h5>
<p class="card-text">${parsedMovies[i].plot}</p>
<p class="card-text"><small class="text-muted"> Year: ${parsedMovies[i].year} <br> Director: ${parsedMovies[i].director} <br> Actors: ${parsedMovies[i].actors}</small>
<div class="voting">
<button id="likebtn">
<i>👍</i>
</button>
<input type="number" id="input1" value="${parsedMovies[i].likes}">
<button id="dislikebtn">
<i>👎</i>
</button>
<input type="number" id="input2" value="${parsedMovies[i].dislikes}">
</div>
</p>
</div>
</div>
</div>
</div>
<div class="card mb-3 bg-dark text-light" style="max-width: 540px;">
<div class="row g-0 ">
<div class="col-md-4 ">
<img src="${parsedMovies[i].image}" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">${parsedMovies[i].title}</h5>
<p class="card-text">${parsedMovies[i].plot}</p>
<p class="card-text"><small class="text-muted"> Year: ${parsedMovies[i].year} <br> Director: ${parsedMovies[i].director} <br> Actors: ${parsedMovies[i].actors}</small>
<div class="voting">
<button id="likebtn">
<i>👍</i>
</button>
<input type="number" id="input1" value="${parsedMovies[i].likes}">
<button id="dislikebtn">
<i>👎</i>
</button>
<input type="number" id="input2" value="${parsedMovies[i].dislikes}">
</div>
</p>
</div>
</div>
</div>
</div>
</div>
`;
let likebtn = document.querySelector("#likebtn");
let dislikebtn = document.querySelector("#dislikebtn");
let input1 = document.querySelector("#input1");
let input2 = document.querySelector("#input2");
likebtn.addEventListener("click", () => {
input1.value = parseInt(input1.value) + 1;
});
dislikebtn.addEventListener("click", () => {
input2.value = parseInt(input2.value) + 1;
});
Your loop is creating multiple time the same ids... An id must be unique.
So, remove all id in the HTML "template" and use a class (I used like-action below) on both the like and dislike buttons.
Then, set ONE event handler for those button, since the action is the same (increment by one). See below:
let likebtns = document.querySelectorAll(".like-action");
likebtns.forEach((button)=>{
button.addEventListener("click", (element) => {
input = element.nextElementSibling
input.value = parseInt(input.value) + 1;
});
});
Have a look at nextElementSibling.
I am having 6 bootstrap cards now I wrote code for storing the every card details in the local storage and also on click the card will get a border now I want is on page refresh I should retain the border of the card
My html code is:
<div class="row">
<div class="col-4" onclick="getGoal(1)">
<div class="card4 mt-3" id="room_1" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_1"><b>I am redecorating</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(2)">
<div class="card4 mt-3" id="room_2" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_2"><b>I am Moving</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(3)">
<div class="card4 mt-3" id="room_3" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_3"><b>I need help with a layout</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(4)">
<div class="card4 mt-3" id="room_4" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_4"><b>I am looking for a species</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(5)">
<div class="card4 mt-3" id="room_5" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_5"><b>I am moving with someone</b></p>
</div>
</center>
</div>
</div>
<div class="col-4" onclick="getGoal(6)">
<div class="card4 mt-3" id="room_6" style="width: 12rem; height:9rem;">
<center>
<div class="card-body">
<p class="card-text mt-4" id="cont_6"><b>Other</b></p>
</div>
</center>
</div>
</div>
</div>
<!--Loop ends-->
<a class="link mt-3"><u>Dont see your room?</u></a>
<div class="row mb-3">
<div class="col-4 mr-5">
« Home
</div>
<div class="col-4 ml-5">
Next »
</div>
</div>
My JS code:
$(document).ready(function(){
// goals
$("#room_1").click(function(){
$("#room_1").toggleClass("blue");
});
$("#room_2").click(function(){
$("#room_2").toggleClass("blue");
});
$("#room_3").click(function(){
$("#room_3").toggleClass("blue");
});
$("#room_4").click(function(){
$("#room_4").toggleClass("blue");
});
$("#room_5").click(function(){
$("#room_5").toggleClass("blue");
});
$("#room_6").click(function(){
$("#room_6").toggleClass("blue");
});
$("#room_7").click(function(){
$("#room_7").toggleClass("blue");
});
$("#room_8").click(function(){
$("#room_8").toggleClass("blue");
});
$("#room_9").click(function(){
$("#room_9").toggleClass("blue");
});
});
var goal = [];
var goalIds = [];
function getGoal(id) {
if (goal.length > 0) {
var data = {
id: id,
content: $("#cont_" + id).text()
}
var x = JSON.stringify(data)
var index = goal.indexOf(x)
if (index == -1) {
goal.push(x);
} else {
goal.splice(index, 1);
}
} else {
var data = {
id: id,
content: $("#cont_" + id).text()
}
var x = JSON.stringify(data);
goal.push(x);
}
localStorage.setItem("goal", JSON.stringify(goal));
goalIds = goal.map(element => JSON.parse(element).id);
console.log(goalIds);
issample();
}
function issample() {
$("#goal").val(goalIds);
console.log(goalIds);
}
function initGoals() {
var storedNames = JSON.parse(localStorage.getItem("goal") || '[]');
goalIds = storedNames.map(element => JSON.parse(element).id);
}
My codepen link is: https://codepen.io/lakshmi123__/pen/xxbzwNP
function initGoals() {
goal = JSON.parse(localStorage.getItem("goal") || '[]');
goalIds = goal.map(element => JSON.parse(element).id);
goalIds.forEach(function(i){$("#room_"+i).addClass('blue');});
}
initGoals();
but event then, you are filling your goalIds variable right with that function,but you are forgetting to fill the goal variable too ;)
I have a view where I am fetching database records in form of bootstrap card. In the each card I have checkboxes which are associated with a database column.
On checking the checkboxes and clicking of the save button I want to hide the card with that record in which I enter that value
How can I achieve this? I tried with the class name of the card but it is hiding all the cards.
$('.insert').click(function() {
var rId = $(this).data('rid');
$.post("#Url.Action("
SetCleaningStatus ", "
HouseKeeping ")", {
id: rId,
InvChk: $('input[data-invchkid=' + rId + ']:checked').length,
ClnChk: $('input[data-cleanid=' + rId + ']:checked').length,
NewLin: $('input[data-nlid=' + rId + ']:checked').length,
DpClean: $('input[data-dcid=' + rId + ']:checked').length
});
$('.Resbook').hide();
});
#model IEnumerable
<RoomTypeView>
<div class="row">
#foreach (var item in Model)
{
<div class="col-3">
<div class="card border rounded DropShadow Resbook">
<div class="card-body">
Room #Html.DisplayFor(modelItem => item.RoomNo)
<button type="button" class="btn btn-default insert" data-rid="#item.RoomId">Save</button><br />
#Html.DisplayFor(modelItem => item.GuestName)<br />
<div class="row">
<div class="col-7 text-center">
#if (item.Status.HasFlag(EnumHkStatus.Cleaning))
{
<input type="checkbox" data-Cleanid="#item.RoomId" name="cstatus" class="form-check-input" />
<label>Cleaning</label>
<br />
}
#if (item.Status.HasFlag(EnumHkStatus.InventoryCheck))
{
<input type="checkbox" data-InvChkid="#item.RoomId" name="cstatus" class="form-check-input" />
<label>Inventory Check</label>
}
</div>
<div class="col-5">
#if (item.NewLinen == null)
{
<input type="checkbox" data-nlid="#item.RoomId" class="form-check-input" />
<label>New Linen</label>
<br />
}
#if (item.DeepCleaning == null)
{
<input type="checkbox" data-dcid="#item.RoomId" class="form-check-input" />
<label>Deep Cleaning</label>
}
</div>
</div>
<div class="row">
<div class="col-8">
<div class="inventory my-1">
<textarea class="form-control breakage" placeholder="Enter Breakage Note" rows="1"></textarea>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-default breakage" data-brid="#item.ReservationID">
<i class="fa fa-file-invoice" style="color:red;"></i>
</button>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="comments my-1">
<textarea class="form-control inventoryms" placeholder="Enter Inventory Missing" rows="1"></textarea>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-default invmissing" data-invmid="#item.ReservationID">
<i class="fa fa-file-invoice" style="color:red;"></i>
</button>
</div>
</div>
#Html.DisplayFor(modelItem => item.Comments)
</div>
</div>
</div>
}
</div>
This $('.Resbook').hide(); is hiding all the cards. How to overcome this? How can I can use that rId to hide that particular card?
it is hiding all the cards
You need to ensure only the related card is hidden. The .insert button is within a .card so you can find the .card it's within using .closest and then use relative finds.
var card = $(this).closest(".card");
$('input[data-invchkid=' + rId + ']:checked', card)
or
card.find('input[data-invchkid=' + rId + ']:checked')
As the .card is also .Resbook (<div class='card Resbook'>) you can use .Resbook instead of .card, eg:
var card = $(this).closest(".Resbook");
$(card).hide();
Giving:
$('.insert').click(function() {
var card = $(this).closest(".card");
var rId = $(this).data('rid');
$.post("#Url.Action("
SetCleaningStatus ", "
HouseKeeping ")", {
id: rId,
InvChk: $('input[data-invchkid=' + rId + ']:checked', card).length,
ClnChk: $('input[data-cleanid=' + rId + ']:checked', card).length,
NewLin: $('input[data-nlid=' + rId + ']:checked', card).length,
DpClean: $('input[data-dcid=' + rId + ']:checked', card).length
});
$(card).hide();
});
Example snippet showing use of .closest() using OPs structure:
$(".insert").click(function() {
$(this).closest(".card").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-3">
<div class="card Resbook">
<div class="card-body">
Room 1
<button type="button" class="btn btn-default insert" data-rid="#item.RoomId">Save</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-3">
<div class="card Resbook">
<div class="card-body">
Room 2
<button type="button" class="btn btn-default insert" data-rid="#item.RoomId">Save</button>
</div>
</div>
</div>
</div>
In the case where the button is not inside the hierarchy of the card to be used, they can be linked together via their data-rid= values.
Add the .data-rid to the .card so that they match:
<div class='card' data-rid='#item.RoomId'/>
then match the two with
$("button").click(function() {
var rid = $(this).data("rid");
var card = $(".card[data-rid=" + rid + "]")
Example snippet:
$(".external-insert").click(function() {
var rid = $(this).data("rid")
var card = $(".card[data-rid=" + rid + "]")
card.hide();
$(this).fadeOut(); // also hide the button
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-3">
<div class="card Resbook" data-rid="1">
<div class="card-body">
Room 1
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-3">
<div class="card Resbook" data-rid="2">
<div class="card-body">
Room 2
</div>
</div>
</div>
</div>
<hr/>
<button type="button" class="btn btn-default insert external-insert" data-rid="1">Save 1</button>
<button type="button" class="btn btn-default insert external-insert" data-rid="2">Save 2</button>
hi guys I have a blog post page and comment and reply system. Everything works fine except one thing:
When I try to add a reply to a comment, I am always replying to the first comment. I think my fault is I can't reach the specific comment id when I click. Here is my html and ajax code:
HTML CODE
<div class="card" style=" margin-bottom:30px;">
<div class="card-header">
<a class="h3">#Model.Header</a>
<br />
<br />
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<p style="font-size:small">
<b>Kategori: </b> #Model.Category.CategoryName ,<b>Makale Sayısı :</b> #Model.Category.Articles.Count()
<b>Yorum Sayısı :</b> #Model.Comments.Count() <br />
<b>Yayımlanma Tarihi: </b> #String.Format("{0: d MMMM yyyy}", Model.Date) ,<b>Etiketler:</b><i class="fa fa-tags"></i> #Model.Tags.Count()
</p>
<p style="font-size:small;">
<img class="rounded-circle img-fluid" style="width:100px;height:100px;" src="#Model.User.Photo" alt="#Model.User.FullName" />
Posted by:
#Model.User.UserName
</p>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<img id="articlephoto" style="width:100%; height:350px" class="rounded float-left" src="#Model.Photo" alt="Card image cap">
</div>
</div>
<div class="row" style="margin-top:20px">
<div class="col-md-12 col-xs-12 col-xl-12">
<p>#Html.Raw(Model.Paragraph)</p>
<p style="font-size:small">
<b>Etiketler:</b>
#foreach (var item in Model.Tags)
{
<span class="tag">#item.TagName,</span>
}
</p>
</div>
</div>
</div>
</div>
<h4>Comments</h4>
<hr />
#foreach (var item in Model.Comments.ToList())
{
<!-- Single Comment -->
<div class="media mb-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body" style="width:400px;">
<h5 class="mt-0">#item.User.UserName</h5>
<p style="word-break:break-all">
#item.Paragraph
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteComment/#item.CommentId">
Delete
</a>
<a class="btn btn-warning replybutton" href="#replyform">
Reply
</a>
}
</p>
<p style="font-size:small"><b>Yorum Tarihi:</b>#String.Format("{0: d MMMM yyyy}", item.Date)</p>
<span id="astar" class=""> #item.CommentId</span>
#foreach (var reply in Model.ReplyComments.Where(x => x.CommentId == item.CommentId).ToList())
{
<div class="media mt-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body">
<h5 class="mt-0">#reply.User.UserName</h5>
<p>#reply.Paragraph</p>
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteReply/#reply.ReplyCommentId">
Sil
</a>
}
</div>
</div>
}
</div>
</div>
<hr />
}
#if (Session["UserId"] != null)
{
<!-- Comments Form -->
<div id="commentform" class="card my-4">
<h5 class="card-header">Yorum Yap:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="comment" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary">Yorum Yap</button>
</form>
</div>
</div>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="reply" name="reply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
}
else
{
<div class="row" style="margin-bottom:30px;">
<div class="col-md-6">
<h3 class="alert- alert-heading">Yorum Yapabilmek İçin Üye Girişi Yapmalısınız.</h3>
</div>
</div>
}
AND my javascript ajax code
<script type="text/javascript">
$(document).ready(function () {
$("#reply").click(function (e) {
var r_comment = $("#replytext").val();
var r_commentid = parseInt($("#astar").html());
$.ajax({
url: '/Home/ReplyComment/',
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("Cevap gönderildi");
window.location.reload();
}
});
});
})
</script>
My problem is that I can't catch the specific comment id when I click the reply button. I am getting the comment id from <span id="astar" class=""> #item.CommentId</span>
"When I try to add a reply to a comment, I am always replying to the first comment. " - it's because all your comments have the same ID and jQuery selects the first matching element.
All comments need to have a unique ID. I don't know what language that loop is in but you need to increment the ID. So astar-1, astar-2, astar-3 etc...
Example;
$(document).ready(function(){
var valueBox = document.getElementById('value-box');
$('.reply').on('click', function(){
var comment = $(this).prev().attr('id');
valueBox.innerHTML += '<br />Reply to comment: ' + comment;
console.log(comment);
});
});
.comment::after {
display: table;
content: ' ';
clear: both;
}
span {
display: block;
float: left;
width: 45%;
}
.reply {
display: block;
float: right;
width: 45%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment">
<span id="comment-1">Yorum 1</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-2">Yorum 2</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-3">Yorum 3</span>
<div class="reply">Cevapla</div>
</div>
<div id="value-box">
</div>