Good day to all, I'm new to js, so I would like to ask you, after executing the function, I add a response with content via innerHTML, but this content should also work with javascript, but it works, so I have to restart the page, how to do it right so that my functions work with the added answer?
Need to run this code
document.querySelectorAll('.btn-comment-like, .btn-comment-dislike').forEach((e) =>
e.addEventListener('click', function(e) {
e.preventDefault()
const commentRatingButtons = this;
const commentRatingId = commentRatingButtons.getAttribute('data-id');
const commentRatingAction = commentRatingButtons.getAttribute('data-action');
const commentTotalRating = document.querySelector(`button[data-comment-rating='${commentRatingId}']`);
const commentMessageRating = document.querySelector(`div[data-comment-message='${commentRatingId}']`);
fetch(`/api/comments/${commentRatingId}/${commentRatingAction}/`, {
method: 'POST',
headers: {
"X-CSRFToken": csrftoken,
"X-Requested-With": "XMLHttpRequest",
},
}).then((response) => response.json()).then((result) => {
if (result['error']) {
commentMessageRating.innerHTML = `
<div class="alert alert-danger rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-hexagon-exclamation"></i> ${result['error']}!
</div>`
} else {
if (commentRatingAction === 'like') {
commentMessageRating.innerHTML = `
<div class="alert alert-success rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-face-smile"></i> Спасибо за оценку, ${result['author']}!
</div>`
} else {
commentMessageRating.innerHTML = `
<div class="alert alert-danger rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-face-frown"></i> Спасибо за критику, ${result['author']}!
</div>`
}
commentTotalRating.innerHTML = `${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i>`
}
})
})
)
after doing this
commentForm.addEventListener('submit', function(e) {
e.preventDefault()
const commentForm = this;
const commentFormSubmit = commentForm.querySelector('#commentSubmit');
const commentArticleId = commentForm.getAttribute('data-article-id');
const commentEmpty = document.querySelector('#emptyComments');
const commentNestedList = document.querySelector('.nested-comments');
commentFormSubmit.innerText = "Ожидаем добавления...";
commentFormSubmit.disabled = true;
fetch(`/api/articles/${commentArticleId}/comments/create/`, {
method: 'POST',
headers: {
"X-CSRFToken": csrftoken,
"X-Requested-With": "XMLHttpRequest",
},
body: new FormData(commentForm),
}).then((response => response.json()))
.then((result) => {
if (result['comment_is_child']) {
const commentParentThread = document.querySelector(`#comment-thread-${result['comment_parent_id']}`);
commentParentThread.innerHTML += `
<ul id="comment-thread-${result['comment_id']}">
<li>
<div class="card mb-3 nth-shadow border-0 rounded-1">
<div class="card-body">
<div class="row">
<div class="col-md-2 d-none d-sm-inline pe-0">
<img src="${result['comment_avatar']}" class="img-fluid rounded-1 nth-img-comment nth-shadow" alt="{{ node.author.username }}">
</div>
<div class="col-md-10">
<div class="d-flex flex-row gap-2">
<div class="card-title">
<h6 class="nth-card-user-username mb-0">${result['comment_author']}</h6>
</div>
<div class="nth-card-title-username">
${result['comment_created_at']}
</div>
</div>
<div class="card-text mb-2">
${result['comment_content']}
</div>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-outline-secondary nth-btn-sm btn-like shadow-none" data-id="${result['comment_id']}" data-action="like" type="button">+1 <i class="fa-solid fa-heart-circle-plus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm btn-dislike shadow-none" data-id="${result['comment_id']}" data-action="dislike" type="button">-1 <i class="fa-solid fa-heart-circle-minus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm shadow-none" type="button" data-comment-rating="${result['comment_id']}">${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i></button>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
`
} else {
if (commentEmpty) {
commentEmpty.remove();
}
commentNestedList.innerHTML += `
<ul id="comment-thread-${result['comment_id']}">
<li>
<div class="card mb-3 nth-shadow border-0 rounded-1">
<div class="card-body">
<div class="row">
<div class="col-md-2 d-none d-sm-inline pe-0">
<img src="${result['comment_avatar']}" class="img-fluid rounded-1 nth-img-comment nth-shadow" alt="{{ node.author.username }}">
</div>
<div class="col-md-10">
<div class="d-flex flex-row gap-2">
<div class="card-title">
<h6 class="nth-card-user-username mb-0">${result['comment_author']}</h6>
</div>
<div class="nth-card-title-username">
${result['comment_created_at']}
</div>
</div>
<div class="card-text mb-2">
${result['comment_content']}
</div>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-outline-secondary nth-btn-sm btn-comment-like shadow-none" data-id="${result['comment_id']}" data-action="like" type="button">+1 <i class="fa-solid fa-heart-circle-plus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm btn-comment-dislike shadow-none" data-id="${result['comment_id']}" data-action="dislike" type="button">-1 <i class="fa-solid fa-heart-circle-minus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm shadow-none" type="button" data-comment-rating="${result['comment_id']}">${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i></button>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
`
}
commentForm.reset();
commentFormSubmit.innerText = "Добавить комментарий";
commentFormSubmit.disabled = false;
commentFormParentField.value = null;
})
})
I would be very grateful if you direct me to the correctness of creating such methods.
If you are feeling lazy to add it to the function then do something like:
let href = "http://"; //the location of your own html file you are working on.
//This will open your file on a new tab
window.open(href, "_blank");
//This will close your own tab.
window.close();
In this way you can close and open the tab again if it does'nt work with: "window.location.reload".
Put all your js code that you want to reload in a function and simply call it again when you want to. You can also use: window.location.reload();
Related
My Basket.js file
function test(){
let baskets = document.querySelectorAll('.basket');
baskets.forEach((basket) => {
$(basket).on("click",function(event){
console.log("clicked")
let productId;
let productName;
let productDiscount;
let productPrice;
let productImage;
let check = $(".gridDisable").attr("id");
if (check === "list") {
let parentDataSort = $(this).closest(".dateSort");
productId = parseInt(parentDataSort.find('.cartProduct').val())
productDiscount = $(this).closest(".dateSort").data("discount");
productName = parentDataSort.data("name");
productDiscount = parentDataSort.data("discount");
productPrice = productDiscount ? parentDataSort.find(".discountResult").data("result") : parentDataSort.data("price");
productImage = parentDataSort.find('.product-img-file').attr('src');
} else {
let parentDataColumn = $(this).closest(".dateSortColumn");
productId = parseInt(parentDataColumn.find('.cartProduct').val())
productDiscount = $(this).closest(".dateSortColumn").data("discount");
productName = parentDataColumn.data("name");
productDiscount = parentDataColumn.data("discount");
productPrice = productDiscount ? parentDataColumn.find(".discountResult").data("result") : parentDataColumn.data("price");
productImage = parentDataColumn.find('.product-image').attr('src');
}
addToBasket(productId, productName, productPrice, productImage);
})
})
}
test();
function addToBasket(productId, productName, productPrice, productImage) {
let cart = localStorage.getItem("cart");
let pCart = JSON.parse(cart) != null ? JSON.parse(cart) : [];
let present_or_not = pCart.findIndex(item => item.productId === productId);
if (cart == null || present_or_not == null || present_or_not === -1) {
let product = {
productId: productId,
productName: productName,
pPrice: productPrice,
quantity: 1,
image: productImage
};
pCart.push(product);
localStorage.setItem("cart", JSON.stringify(pCart));
} else {
let actual_stored_product = pCart[present_or_not];
pCart.splice(present_or_not, 1);
let actual_qty = actual_stored_product.quantity == null || actual_stored_product.quantity === "" ? 0 : actual_stored_product.quantity;
actual_stored_product.quantity = parseInt(actual_qty) + 1;
pCart.push(actual_stored_product);
localStorage.setItem("cart", JSON.stringify(pCart));
}
swal({
title: "Səbətə əlavə olundu",
icon: "success",
button: "Bağla",
});
let count = JSON.parse(localStorage.getItem("cart")).length;
$(".basket_count").text(count);
}
My active.js file
function showFilteredPriceProduct(min, max, isNew) {
$.get("/product/price?min=" + min + "&max=" + max + "&isNew=" + isNew, function (data) {
$("#column").empty();
$("#grid").empty();
if (data.data.length <= 10) {
$("#pagen").hide();
} else {
$("#pagen").show();
}
$.each(data.data, function (key, v) {
let item_content = `<div class="col-md-12 ml-4 my-3 py-2 dateSortColumn" data-name="${v.name}" data-price="${v.price}" data-discount="${v.isDiscount}">
${v.isNew ? `<div class="ribbon text-center" >Yeni<br></div>` : `<small style="display:none !important"></small>`}
${v.isDiscount ? `<div class="discount">- ${v.discount} %</div>` : `<small style="display:none !important"></small>`}
<div class="row bg-white">
<div class="col-md-3 mt-1">
<div class="container" id="wishlist">
<i class="far fa-heart js-heart heart"></i>
</div>
<img class="img-fluid img-responsive rounded product-image" src="${v.files[0].url}" />
</div>
<div class="col-md-6 mt-1">
<h5 class="detailLink">${v.name}</h5>
<div class="ratings-cart d-flex flex-row">
<div class="ratings mr-2">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
</div>
</div>
</div>
<div class="align-items-center align-content-center col-md-3 border-left mt-1">
<label>
<input class="cartProduct" style="visibility: hidden!important;" th:value="${v.id}"
type="text">
</label>
<div class="d-flex flex-column justify-content-start">
${v.isDiscount ? `<div>
<h4 class="mr-1 product-price discountResult">${v.price - (v.price * v.discount / 100)}.00</h4>
</div>` : `<h4 class="mr-1 product-price">₼ ${v.price}.00</h4>`}
${v.isDiscount ? `<del>
<h4 style="font-size:14px;" class="mr-1 product-price">₼ ${v.price}.00</h4>
</del>` : `<small style="display:none;"></small>`}
</div>
<h6 class="text-success">Baxış sayı:<small class="productCount">${v.count}</small></h6>
<div class="d-flex flex-column mt-4">
<button class="btn btn-sm basket" type="button">Səbətə əlavə et</button>
</div>
</div>
</div>
</div>`
let grid_items = `<div class="col-12 col-sm-6 col-md-12 col-xl-6 dateSort" data-name="${v.name}" data-price="${v.price}">
<div class="single-product-wrapper">
${v.isNew ? `<div class="ribbon text-center" >Yeni<br></div>` : `<small style="display:none !important"></small>`}
${v.isDiscount ? `<div class="discount">- ${v.discount} %</div>` : `<small style="display:none !important"></small>`}
<div class="product-img">
<img alt="" class="product-img-file" src="${v.files[0].url}" />
</div>
<div class="product-description d-flex align-items-center justify-content-between">
<div class="product-meta-data">
<label>
<input class="cartProduct" style="visibility: hidden !important;" value="${v.id}" type="text" />
</label>
<div class="line"></div>
<div class="d-flex flex-column justify-content-start dataPrice">
${v.isDiscount ? `<div>
<p class="product-price discountResult"> ₼ ${v.price - (v.price * v.discount / 100)}.00 </p>
</div>` : ` <p class="product-price">₼ ${v.price}.00 </p>`}
${v.isDiscount ? `<del><h4 style="font-size:14px;" class="mr-1 product-price">₼ ${v.price}.00</h4>
</del>` : `<small style="display:none"></small>`}
</div>
<a href="/detail/${v.id}">
<h6 class="productName">${v.name}</h6>
</a>
<button class="basket" type="button">Səbətə əlavə et</button>
</div>
<div class="ratings-cart text-right">
<div class="ratings">
<i aria-hidden="true" class="fa fa-star"></i>
<i aria-hidden="true" class="fa fa-star"></i>
<i aria-hidden="true" class="fa fa-star"></i>
<i aria-hidden="true" class="fa fa-star"></i>
<i aria-hidden="true" class="fa fa-star"></i>
</div>
<small> Baxış sayı: <small>${v.count}</small> </small>
</div>
</div>
</div>
</div>
`
$("#grid").append(grid_items);
$("#column").append(item_content);
})
});
}
Hi everyone my simple project using thymeleaf and javascript code loading my project my add basket service normal working but sort change sort data returns spring boot backend service and append html code using javascript and jquery click event not working my add basket service
I wanna to hide sorting icons by default and show them by clicking the column header name. This is my .cshtml code:
#model string[]
<style>
</style>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<div class="tableHeader" id ="table">
<div class="card w-100 mb-1 border-0">
<div class="card-dark-mode-body text-dark headerRow fw-bolder mainColor" >
<div class="row p-2">
#foreach(var prop in Model)
{
<div class="col text-center d-table sortable" >
<div class="btn-group" id="sorting" onclick="sortingVisibility()">
<p class="mb-0 d-lg-table-cell align-middle" id="columnName" style='padding-top:3px'>
#prop
<div class="btn-group-vertical" style='padding-left: 20px;' id="divIcon">
<a href="/Administracija/Ocitavanja/Index?OrderBy=#prop&Sorting=asc" class="btn btn-xs btn-link p-0">
<i class="fa fa-sort-up" style='color:white;' id="sortUpIcon" aria-hidden="true"></i>
</a>
<a href="/Administracija/Ocitavanja/Index?OrderBy=#prop&Sorting=desc" class="btn btn-xs btn-link p-0">
<i class="fa fa-sort-down" style='color:white;' id="sortDownIcon" aria-hidden="true"></i>
#*<span class="glyphicon glyphicon-triangle-bottom" style='color:white;'></span>*#
</a>
</div>
</p>
</div>
</div>
}
</div>
</div>
</div>
</div>
#*location.href='/Administracija/Ocitavanja/Index?OrderBy=#prop&Sorting=desc'*#
<script>
function sortingVisibility()
{
var iconUp = document.getElementById("sortUpIcon");
var iconDown = document.getElementById("sortDownIcon");
var div = document.getElementById("divIcon");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
I tried to do like this but its not working on click it only hide the icon and doesnt change anything.
Can anyone give me some hints about this?
In order to hide the div, you have to initially set the display property of the div to none and then we have to set the display property to block or none.
Below I have modified your code with the changes.
#model string[]
<style>
</style>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<div class="tableHeader" id ="table">
<div class="card w-100 mb-1 border-0">
<div class="card-dark-mode-body text-dark headerRow fw-bolder mainColor" >
<div class="row p-2">
#foreach(var prop in Model)
{
<div class="col text-center d-table sortable" >
<div class="btn-group" id="sorting" onclick="sortingVisibility()">
<p class="mb-0 d-lg-table-cell align-middle" id="columnName" style='padding-top:3px'>
#prop
<div class="btn-group-vertical" style='padding-left: 20px;' id="divIcon">
<a href="/Administracija/Ocitavanja/Index?OrderBy=#prop&Sorting=asc" class="btn btn-xs btn-link p-0">
<i class="fa fa-sort-up" style='color:white; display: none' id="sortUpIcon" aria-hidden="true"></i>
</a>
<a href="/Administracija/Ocitavanja/Index?OrderBy=#prop&Sorting=desc" class="btn btn-xs btn-link p-0">
<i class="fa fa-sort-down" style='color:white; display: none' id="sortDownIcon" aria-hidden="true"></i>
#*<span class="glyphicon glyphicon-triangle-bottom" style='color:white;'></span>*#
</a>
</div>
</p>
</div>
</div>
}
</div>
</div>
</div>
</div>
#*location.href='/Administracija/Ocitavanja/Index?OrderBy=#prop&Sorting=desc'*#
<script>
function sortingVisibility()
{
var iconUp = document.getElementById("sortUpIcon");
var iconDown = document.getElementById("sortDownIcon");
var div = document.getElementById("divIcon");
if ( iconUp.style.display == "none" || iconDown.style.display == "none";){
iconUp.style.display == "none";
iconDown.style.display =="block";
} else {
iconUp.style.display == "block";
iconDown.style.display =="none";
}
}
I am trying to hide / show comment replies.
I tried a few methods but couldn't get class with dynamic ids.
My html structure is like this :
<div class="display-comments">
<div class="form-group border-bottom" id="comment-1">
//level - 1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom parentOF-1" id="comment-2">
//level-2 parentOF-1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom parentOF-2" id="comment-3">
//level-3 parentOF-2
</div>
<div class="form-group border-bottom" id="comment-4">
//level-4 doesnt have child
</div>
</div>
I tried like in the following example with different variations.
$(document).on('click', '.show_reply', function(e) {
e.preventDefault();
var commet-id = $('comment-').val();
var parentOF = $('parentOF-').val();
$(this).text() == "show replies" ? $(this).text("show replies") : $(this).text("hide replies");
$(this).closest('parentOF-').nextUntil('parentOF-').slideToggle();
});
But couldn't make it work. Thanks for any help.
You could Hide At comment div's all class that contains parentOf- class ,
$("div[class*='parentOF-']").hide();
then in each button attach event that show child comment on click , otherwise hide child comment and all it's children using recuresive function described in the snippet :
function hideRecurssive(id) {
let $child = $(`.parentOF-${id}`);
if($child.length>0) {
var newId = $child.attr("id")
// get last char that refer to child comment
newId = newId.charAt(newId.length - 1);
$child.slideUp();
var btn = $child.find(".show_reply");
if(btn.length) btn.text("show replies");
hideRecurssive(newId);
};
}
Here a working snippet as I understand :
$(function($) {
$("div[class*='parentOF-']").hide();
$(document).on('click', '.show_reply', function(e) {
e.preventDefault();
let id = $(this).attr("id");
if( $(this).text() == "show replies" ) {
$(this).text("hide replies")
let $childComment = $(`.parentOF-${id}`)
$childComment.slideDown();
} else if($(this).text() === "hide replies") {
hideRecurssive(id);
$(this).text("show replies")
}
});
});
function hideRecurssive(id) {
let $child = $(`.parentOF-${id}`);
if($child.length>0) {
var newId = $child.attr("id")
// get last char that refer to child comment
newId = newId.charAt(newId.length - 1);
$child.slideUp();
var btn = $child.find(".show_reply");
if(btn.length) btn.text("show replies");
hideRecurssive(newId);
};
}
.hide {
color: red;
}
.unhide {
color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<div id="display_comment" class="col-12">
<div class="form-group border-bottom " id="comment-6">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Çeviri, yabancı dili İnternet&#39;teki içerik deryasını tam olarak anlamak için yeterli olmayan kullanıcılar tarafından tercih ediliyor. Bununla birlikte Google Çeviri, her zaman mükemmel t</div>
</div>
<div class="col-12 sttime">2021-01-09 02:23:38
<button type="button" class="btn btn-primary btn-xs reply" id="6">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="6" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-6" id="comment-7">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Translate aracı halihazırda 100&#39;den fazla dil arasında tercüme yapıyor.</div>
</div>
<div class="col-12 sttime">2021-01-09 02:23:56
<button type="button" class="btn btn-primary btn-xs reply" id="7">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="7" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-7" id="comment-8">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Translate çeviriler için yakın zamana kadar Avrupa Parlamentosu ve Birleşmiş Milletler gibi büyük kuruluşların verilerini kullanıyordu. Çeviriler ayrıca sözlük bilgileri ve kullanıcılar tarafın</div>
</div>
<div class="col-12 sttime">2021-01-09 02:24:19
<button type="button" class="btn btn-primary btn-xs reply" id="8">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="8" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-8" id="comment-11">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">rew rew ew wre</div>
</div>
<div class="col-12 sttime">2021-01-09 18:10:46
<button type="button" class="btn btn-primary btn-xs reply" id="11">Reply <i class="fas fa-share" aria-hidden="true"></i></button>
</div>
</div>
</div>
<div class="form-group border-bottom " id="comment-9">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Çeviri nasıl kullanılır? Google Translate anlaşılır bir arayüze sahip ancak keşfedilecek birçok özelliği var.</div>
</div>
<div class="col-12 sttime">2021-01-09 02:24:43
<button type="button" class="btn btn-primary btn-xs reply" id="9">Reply <i class="fas fa-share" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
Updated as per request. This will allow you to show nested comments and hide them. If you hide a parent comment then all nested comments will be hidden.
N.B. I changed your parentOF- to childOF- because it didn't make sense. You can just change all incidences of the class name in the code below if you'd like to keep it.
All the code is fully commented.
// Add dynamic click event listener
$(document).on('click', '.show_reply', function(e) {
// Toggle button text
if ($(this).text() == "show replies") {
$(this).text("hide replies");
} else {
$(this).text("show replies");
}
// Get comment-id from parent element
commentID = $(this).parent().attr("id");
// Just get id
commentID = commentID.replace("comment-", "");
// Store element
el = $(".childOF-" + commentID);
// Check if element is visible
if (el.is(':visible')) {
// Check for nested comments if hiding
hideNested(commentID);
// Hide element
el.slideUp();
} else {
// Show element
el.slideDown();
}
});
function hideNested(nestedID) {
// Find element that is child of the one passed
nested = $(".childOF-" + nestedID)
// Check if nested comment exists
if (nested.length == 0) {
// Exit function if it does not
return;
}
// Hide comment
nested.slideUp();
// Update button text
nested.find("button.show_reply").text("show replies");
// Check for further nested comments
hideNested(nested.attr("id").replace("comment-", ""));
}
div[class^='childOF'],
div[class*=' childOF'] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="display-comments">
<div class="form-group border-bottom" id="comment-1">
//level - 1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
<div class="form-group border-bottom childOF-1" id="comment-2">
//level-2 childOF-1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom childOF-2" id="comment-3">
//level-3 childOF-2
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom childOF-3" id="comment-4">
//level-4 childOF-3
</div>
</div>
<div class="form-group border-bottom" id="comment-5">
//level-5 doesnt have child
</div>
</div>
I want to get the text between the div tag by clicking on the button event
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-secondary">
<div class="price-header">
<h3 class="title text-white">Gold Plan</h3>
<div class="price">
<span class="dollar">₹</span> 7000
</div>
<span class="permonth">3 months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-third">
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div class="price text-primary">
<span class="dollar">₹</span> 12000
</div>
<span class="permonth">6 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-fourth">
<div class="price-header">
<h3 class="title text-white">Platinum Plan</h3>
<div class="price text-white">
<span class="dollar">₹</span> 15000
</div>
<span class="permonth">12 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
I have this type of divs its around three or four I want to detect the value 12000 and the month 6 Months by clicking on this button
How can I achieve that.
Try
$(".price-footer .btn").on( "click", function(event) {
const parent = $(this).parents('.pricing-table');
const priceText = $('.price', parent).text().trim();
const priceParts = priceText.split(' ');
console.log(`priceText: ${priceParts[1]}`);
// Output: "priceText: 12000"
const permonthText = $('.permonth', parent).text().trim();
console.log(`permonthText: ${permonthText}`);
// Output: "permonthText: 6 Months"
});
Demo - https://codepen.io/vyspiansky/pen/MWybEEr
You can add ids to the elements you want to extract the contents of, then you can use document.getElementById(id) to get those elements, and use .innerText to extract the string contents.
Then with a string.replace() you can remove any non-numerical values, and convert the monetary value into a number.
const dollarAmount = parseFloat(document.getElementById("dollar-info").innerText.replace(/[^0-9.]/g, ''))
const month = document.getElementById("month-info").innerText
console.log(dollarAmount)
console.log(month)
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div id="dollar-info" class="price text-primary">
<span class="dollar">₹</span>12000.80
</div>
<span id="month-info" class="permonth">6 Months</span>
</div>
Assuming you have many price tables you can loop each table as below example. You can wrap you data in a certain class and get the text value of that class div. Click the button on the to get the value in the example below
$(document).ready(function(){
$('.pricing-table').each(function(){
var $table = $(this);
$table.on('click', '.btn-primary', function(){
var price = $table.find('.price').text().trim();
var permonth = $table.find('.permonth').text().trim();
alert("price is " + price + " for " + permonth);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-third">
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div class="price text-primary">
<span class="dollar">₹</span> 12000
</div>
<span class="permonth">6 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal"
class="btn btn-primary btn-block btn-lg" href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
There are so many options to do this. Here is my example with the snippet and code sandbox.
// jquery
const findValues = (target, value) => target.parents().eq(1).find(value);
$(document).on("click", ".btn", (e) => {
const $target = $(e.target);
// dollar is optional
const $dollar = findValues($target, ".dollar");
const $value = findValues($target, ".value");
const $month = findValues($target, ".permonth");
$("#test").text(`${$dollar.text()} ${$value.text()} ${$month.text()}`);
});
// // vanilla js
const test1 = document.querySelector("#test1");
document.querySelectorAll(".btn").forEach((btn) => {
btn.addEventListener("click", ({ target }) => {
const nodes = target.parentNode.parentNode;
const dollar1 = nodes.querySelector(".dollar");
const value1 = nodes.querySelector(".value");
const month1 = nodes.querySelector(".permonth");
test1.innerText = `${dollar1.textContent} ${value1.textContent} ${month1.textContent}`;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-secondary">
<div class="price-header">
<h3 class="title text-white">Gold Plan</h3>
<div class="price">
<span class="dollar">₹</span> <span class="value">7000</span>
</div>
<span class="permonth">3 months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-lg"
href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-third">
<div class="price-header">
<h3 class="title text-white">Diamond Plan</h3>
<div class="price text-primary">
<span class="dollar">₹</span> <span class="value">12000</span>
</div>
<span class="permonth">6 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-lg"
href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-4">
<div class="pricing-table pricing-fourth">
<div class="price-header">
<h3 class="title text-white">Platinum Plan</h3>
<div class="price text-white">
<span class="dollar">₹</span> <span class="value">15000</span>
</div>
<span class="permonth">12 Months</span>
</div>
<div class="price-footer">
<a data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-lg"
href="javascript:void(0);">Book an
Online Appointment</a>
</div>
</div>
</div>
<div id="test"></div>
<div id="test1"></div>
https://codesandbox.io/s/eager-voice-2w640?file=/src/index.js
I have following html structor the content is added dynamically
<div class="media text-muted pt-3">
<img data-src="holder.js/32x32?theme=thumb&bg=d32f2f&fg=d32f2f&size=1" alt="todo" class="mr-2 rounded">
<div class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<div class="d-flex justify-content-between align-items-center w-100">
<strong class="text-gray-dark">{{ $ticketValue->title }}</strong>
</div>
<br>
<div class="d-flex justify-content-between align-items-center w-100">
<span class="d-block">
<strong>Erstellt von {{ $ticketValue->description }}</strong>
</span>
<button type="button" class="closing-ticket" data-ticket-id="{{ $ticketValue->id }}">
<i class="fas fa-check"></i>
</button>
</div>
</div>
</div>
If the user click on the button I would like to change the data-src of the current parent image tag.
So far I have done this:
this.closingTicket.click((e) => {
let _this = $(e.currentTarget);
axios.post('ticket/close/' + this.elements.closingTicket.attr('data-ticket-id'))
.then((response) => {
_this.hide(); // hides buttons
// trying to find the image and change its data-src
_this.parent().parent().parent().find('img').data('src', 'holder.js/32x32?theme=thumb&bg=64dd17&fg=64dd17&size=1');
})
.catch((error) => {
// error
})
});