MVC javascript display selected data - javascript

First of all, I list the e-mail from coming ActionResult in the first cycle.
I want to see the details by clicking on the listed data. I open with the help of jQuery details. The problem arises in this section. in this case ,the opening of the details of the first mail in the detail of each row.
There are details of the message in the second loop.To connect to the two loops in a guid font was coming. (MessageId).
id=messageId (guid type)
mailing list
<div class="message-list-container">
<div class="message-list" id="message-list">
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
<span class="sender" title="#item.From">
#item.From
</span>
<span class="time">#mvcHelper.saatAyarla(item.Date)</span>
#if(item.Attachments.Any())
{
<span class="attachment">
<i class="ace-icon fa fa-paperclip"></i>
</span>
}
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
</div>
}
</div>
</div>
mailing details
<!--Messsage details-->
#foreach (var item in Model)
{
<!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
<div class="message-header clearfix">
<div class="pull-left">
<span class="blue bigger-125"> #item.Subject </span>
<div class="space-4"></div>
<i class="ace-icon fa fa-star orange2"></i>
<img class="middle" alt="John's Avatar" src="/Areas/admin/Content/images/avatars/avatar.png" width="32" />
#item.From
<i class="ace-icon fa fa-clock-o bigger-110 orange middle"></i>
<span class="time grey">#mvcHelper.saatGoster(item.Date)</span>
</div>
</div>
<div class="hr hr-double"></div>
<div class="message-body">
<p>
#item.TextBody
</p>
</div>
<div class="hr hr-double"></div>
<!--Eklenti paneli-->
<div class="message-attachment clearfix">
#if (item.Attachments.Any())
{
<div class="attachment-title">
<span class="blue bolder bigger-110">Eklentiler</span>
<span class="grey">(#item.Attachments.Count() Dosya)</span>
</div>
<ul class="attachment-list pull-left list-unstyled">
#foreach (var attachment in item.Attachments)
{
<li>
<a href="#" class="attached-file">
<i class="ace-icon fa fa-file-o bigger-110"></i>
<span class="attached-name">#mvcHelper.getAttachmentName(attachment.ToString())</span>
</a>
<span class="action-buttons">
<a href="#">
<i class="ace-icon fa fa-download bigger-125 blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o bigger-125 red"></i>
</a>
</span>
</li>
}
</ul>
}
</div>
</div><!-- /.message-content -->
}
<!--Eklenti paneli Son-->
<!--message details end-->
loop connecting two points.
first foreach = <div id="#item.MessageId" class="message-item">
//Places where the problem is. They need to be connected.
second foreach = <!-- <div class="hide message-content" id="id-message-content">-->
<div class="hide message-content" id="#item.MessageId">
var content = message.find('.message-content:last').html($('#id-message-content').html());
jQuery code
$('.message-list .message-item .text').on('click', function () {
var message = $(this).closest('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').remove();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message
.addClass('message-inline-open')
.append('<div class="message-content" />');
var content = message.find('.message-content:last').html($('#id-message-content').html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});

Your first problem is that you are creating multiple elements with identical id properties. This makes your HTML invalid.
Here is the problem code:
#foreach (var item in Model)
{
<div id="#item.MessageId" class="message-item">
...
#foreach (var item in Model)
{
<div class="hide message-content" id="#item.MessageId">
...
For each message in your model, this will create 2 <div> elements whose id has the value of the #item.MessageID variable. The second of these is and illegal element because it has the same ID as an earlier element. You will need to make these <div>s have unique IDs.
The second problem is:
When you run
var content = message.find('.message-content:last').html($('#id-message-content').html());
this part:
$('#id-message-content').html()
cannot find anything because there is no element whose id is "id-message-content". Also every time you open the message, you are appending another "message-content" div into the message-item. This is not necessary.
To fix these issues, you can change the code like this:
First loop:
#foreach (var item in Model)
{
<div data-messageid="#item.MessageId" class="message-item">
...
<span class="summary">
<span class="text">
#item.Subject
</span>
</span>
<div class="message-content" hidden></div>
...
Second loop:
#foreach (var item in Model)
{
<div class="hide message-content" id="message-content-#item.MessageId">
...
jQuery:
$('.message-list .message-item .text').on('click', function () {
var message = $(this).parents('.message-item');
//if message is open, then close it
if (message.hasClass('message-inline-open')) {
message.removeClass('message-inline-open').find('.message-content').hide();
return;
}
$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
setTimeout(function () {
$('.message-container').find('.message-loading-overlay').remove();
message.addClass('message-inline-open');
var content = message.find(".message-content");
content.show();
content.html($('#message-content-' + message.data("messageid")).html());
//remove scrollbar elements
content.find('.scroll-track').remove();
content.find('.scroll-content').children().unwrap();
content.find('.message-body').ace_scroll({
size: 150,
mouseWheelLock: true,
styleClass: 'scroll-visible'
});
}, 500 + parseInt(Math.random() * 500));
});

Solved
public static class mvcHelper
{
public static string variableReplace(string id)
{
string yazi = null;
if (id != null)
{
yazi = id.Replace('#', 'a').ToString();
}
else
{
yazi = id;
}
return yazi;
}
}
<div data-messageid="#mvcHelper.variableReplace(item.MessageId)" class="message-item">
<div class="hide message-content" id="message-content-#mvcHelper.variableReplace(item.MessageId)">

Related

No Console Log Output When Clicking Plus Icon in Unordered List

I have an ul (unordered list) which contains several li (list items) when I click on the + sign left to li, console log should output "description expanded" For the two first li, it works just fine, but not for any other li's. The html code by default includes only 2 li's. any li after that is added through the form. However, any new li does not produce the console log output. Which means they're not responding to clicks. I'm using jQuery to listen for click events. When clicking on the icon.
project link http://pctechtips.org/apps/todo/
//variables
//todoList array to hold (title, description) for every todo tiem
var todoList = []; //{title: "value", desc: "value"},
var numId = 2; //num is for desc paragraph id eg <p id="plus-3">
/*
* Script main body
*/
$(document).ready(function() {
//hide form when doc loads first time
$("#submit-form").hide();
//hide list item description <p>
$(".item-desc").hide();
//listener for show hide form functionality
$("#add-todo").click(function() {
toggleForm();
return false; //return false to prevent page reload
});
//listener for add new item form (submit button)
$(".btn").click(function() {
console.log("submit item");
addToList();
});
//listener for expanding li description
$(".plus").click(function() {
console.log("description expanded")
var plusId = $(this).attr("id"); //grabbing id of plus sign
showDescription(plusId);
return false;
});
});
//functionality for show / hide form
function toggleForm() {
if($("#submit-form").is(":hidden")) {
console.log("form exapnded");
$("#submit-form").show("slow");
$("#form-icon").removeClass("fa-plus-square-o");
$("#form-icon").addClass("fa-minus-square-o");
}
else {
console.log("form hidden");
$("#submit-form").hide("slow");
$("#form-icon").removeClass("fa-minus-square-o");
$("#form-icon").addClass("fa-plus-square-o");
}
}
//add new item to todo list items
function addToList() {
numId++;
//getting data from input fields
var todoTitle = $("#todo-title").val();
var todoDesc = $("#todo-desc").val();
//checking user input
if(todoTitle == "" || todoDesc == "") {
alert("fill in all fields!");
}
else {
console.log(todoTitle + "\n" + todoDesc);
//adding values to array
todoList.push({title: todoTitle, desc: todoDesc},);
//adding new li to ul
var ul = document.getElementById("list");
var li = document.createElement("li");
$(li).addClass("list-group-item justify-content-between align-items-center");
$(li).append(($('<i id="plus-'+numId+'" class="plus fa fa-plus-square-o left" aria-hidden="true"></i>')));
$(li).append(($('<span class="left marg-left">'+todoTitle+'</span>')));
$(li).append(($('<i class="fa fa-trash-o right" aria-hidden="true"></i>')));
$(li).append(($('<i class="fa fa-pencil right marg-right pr-2" aria-hidden="true"></i>')));
ul.appendChild(li);
}
}
//expanding description under for each todo
function showDescription(plusId) {
//getting the number from id
var num = plusId.substring(plusId.indexOf("-")+1);
//checking for hide / show description paragraph
if($("#desc-"+num).is(":hidden")) {
$("#desc-"+num).show("slow");
$("#desc-"+num).removeClass("fa-plus-square-o");
$("#desc-"+num).addClass("fa-minus-square-o");
}
else {
$("#desc-"+num).hide("slow");
$("#desc-"+num).removeClass("fa-minus-square-o");
$("#desc-"+num).addClass("fa-plus-square-o");
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>TodoList App</title>
<!-- bootstrap, fontawsome cdn -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- local stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- jquery cdn -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- local javascript -->
<script type="text/javascript" src="js/todo.js"></script>
</head>
<body>
<!-- navbar -->
<nav class="navbar navbar-expand-lg navbar-drak bg-dark mb-4">
<a class="navbar-brand" href="#"><i class="fa fa-thumb-tack" aria-hidden="true"></i> Todo<strong>List</strong></a>
</nav>
<!-- /navbar -->
<!-- todoList -->
<div class="container">
<div class="add-item text-white text-center col-sm-12 col-md-10 col-lg-8 mb-4">
<a id="add-todo" class="new-todo text-white text-center" href=""><i id="form-icon" class="fa fa-plus-square-o" aria-hidden="true"></i> Enter new todo item</a>
<div id="submit-form" class="form-hide text-center col-sm-12 col-md-12 col-lg-8">
<form class="">
<div class="form-group">
<input type="text" class="form-control" id="todo-title" placeholder="Todo Title" value="Pay Car Insurance">
</div>
<div class="form-group">
<input type="text" class="form-control" id="todo-desc" placeholder="Todo Description" value="This is to pay car insurance">
</div>
<button type="button" class="btn btn-primary btn-lg col-12">Submit Todo</button>
</form>
</div>
<!-- horizontal line -->
<hr>
<!-- list items -->
<h1 class="heading-4">Todo List Items</h1>
<ul id="list" class="list-group mt-4 pb-4">
<li class="list-group-item justify-content-between align-items-center">
<i id="plus-1" class="plus fa fa-plus-square-o left" aria-hidden="true"></i>
<span class="left marg-left">Pay Car Insurance </span>
<i class="fa fa-trash-o right" aria-hidden="true"></i>
<i class="fa fa-pencil right marg-right pr-2" aria-hidden="true"></i>
</li>
<p id="desc-1" class="item-desc bg-white">Helloooooooooo this is description</p>
<li class="list-group-item justify-content-between align-items-center">
<i id="plus-2" class="plus fa fa-plus-square-o left" aria-hidden="true"></i>
<span class="left marg-left">Pay Car Insurance </span><i class="fa fa-trash-o right" aria-hidden="true"></i>
<i class="fa fa-pencil right marg-right pr-2" aria-hidden="true"></i>
</li>
<p id="desc-2" class="item-desc bg-white">Helloooooooooo this is description</p>
</ul>
</div>
</div>
</body>
</html>
ok for dynamically added elements the even listener needs to be defined at the root / document level. so
$("class").on("click", function() { });
will not work. It needs to be
$(document).on("click", ".class", function() { });
Thanks to "MADDY BLACKLISTED" above pointed me in right directions
Use
$(document).on("click", ".plus", function() {
console.log("description expanded")
var plusId = $(this).attr("id"); //grabbing id of plus sign
showDescription(plusId);
return false;
});
Instead of having a static click listener defined at document load.

How to get product name and image dynamically using jQuery?

Actually I am doing add to cart functionality using jQuery. On click of add to cart button product name and image should come. Statically I can do but how to get the product name and image dynamically for all divs is what I want. Please somebody help with this.
This is my HTML markup:
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/barcunda-black.jpg" class="lazy-loaded"/>
<h4>Barcunda Black</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/bruno-white.jpg" class="lazy-loaded"/>
<h4>Bruno White</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/fantasy-brown.jpg" class="lazy-loaded"/>
<h4>Fantasy Brown</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/iceberg.jpg" class="lazy-loaded"/>
<h4>Iceberg</h4>
</div>
</div>
<div class="col-sm-4">
<div class="prdtitem" id="anaconda">
<div class="cartBg">
<a href="#cart" onclick="addToCart()">
<div class="enqry-cart pull-left">
<i class="fa fa-shopping-cart pull-left" aria-hidden="true"></i>
<span class="pull-left">add to enquiry cart</span>
</div>
</a>
</div>
<img src="images/mercury-white.jpg" class="lazy-loaded"/>
<h4>Mercury White</h4>
</div>
</div>
And here my jQuery code:
$(document).ready(function(){
//alert("coming");
var cart = [];
$(function () {
if (localStorage.cart) {
cart = JSON.parse(localStorage.cart);
// console.log(cart);
showCart();
}
});
});
function addToCart() {
how to get product name and image here for all divs?
// alert(price);alert(name);alert(qty);return false;
// update qty if product is already present
for (var i in cart) {
if(cart[i].Product == name) {
cart[i].Qty = qty;
showCart();
saveCart();
return;
}
}
// create JavaScript Object
var item = { Product: name, Price: price, Qty: qty };
//console.log(item);return false;
// alert(item);return false;
cart.push(item);
console.log(cart);return false;
saveCart();
showCart();
}
function deleteItem(index){
//alert(index);return false;
cart.splice(index,1); // delete item at index
showCart();
saveCart();
}
function saveCart() {
if ( window.localStorage) {
localStorage.cart = JSON.stringify(cart);
}
}
Add this to your addToCart() function on the first line:
var $parent = $(this).parents('.prdtitem');
var productName = $parent.find('h4').text();
var productImage = $parent.find('img').attr('src');
UPDATE
function addToCart(elem){
var $parent = $(elem).parents('.prdtitem');
var productName = $parent.find('h4').text();
var productImage = $parent.find('img').attr('src');
// then the rest of your existing code
}
I see a very little jQuery involved in your addToCart function. You could simply refer it's parent container to get the source attribute of the image and the product title text:
First of all, change the way button is clicked, instead of using inline function, you could add a class reference on it, and fire the addToCart button as callback:
...
$('.btn-add').on('click', addToCart);
function addToCart() {
var container = $(this).parents('.prdtitem');
var thumbnailImage = container.find('img.lazy-loaded').attr('src');
var productTitle = container.find('h4').text();
// ... rest of your code
}
Now you got the image source within the thumbnailImage variable and the title in the productTitle.
Create a click event:
$('.cartBg a').click(function(){
var img = $(this).closet('.cartBg').find('img').attr('src');
var title = $(this).closet('.cartBg').find('h4').text();
addToCart();
alert(title);
});
You can use your function like this -
JAVASCRIPT
function addToCart(obj){
var product_name = $(obj).closest('.prdtitem').find('h4').text();
var image_src = $(obj).closest('.prdtitem').find('img.lazy-loaded').attr('src');
alert(product_name,image_src);
}
In element you use this function call like this onclick=addToCart(this).

how to dynamically set text to an element in jquery

i have an onclick function that that calls a changeName function anytime a click event on that element happens.
function changeName() {
var frag = $('<span class="Name">change me</span>');
$( ".list" ).prepend(frag);
var x =[];
$('.ch-gname').each(function(index, obj)
{
x.push($(this).text());
for(i=0; i<x.length; i++) {
$('.Name').text(x[i]);}}});
$('#action').on('click', changeName);
HTML
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">Greenhouse</span>
</div>
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">tree house</span>
</div>
<div>
<a href="#0" class="cb-pgcar"</a>
<span class="ch-gname">light house</span>
</div>
<div class="list">
</div>
<div class="list">
</div>
<div class="list">
</div>
i want to able to change the text of the class Name to the text of class ch-gname. My function gives me only the last text text(lighthouse) for the three links.Any help please
The function changeName() has $('#action').on('click', changeName); but i do not see any element with id 'action'. Anyhow i've made necessary changes in order to make it work.
Added Action id to the elements
Changed the $('.Name').text(x[i]); to $('.Name')[i].innerHTML = x[i];
Look at the below example
function changeName() {
var frag = $('<span class="Name">change me</span>');
$(".list").prepend(frag);
var x = [];
$('.ch-gname').each(function(index, obj) {
x.push($(this).text());
});
for (i = 0; i < x.length; i++) {
$('.Name')[i].innerHTML = x[i];
}
}
$('#action').on('click', changeName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">Greenhouse</span>
</div>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">tree house</span>
</div>
<div>
<a href="#0" class="cb-pgcar" </a>
<span id="action" class="ch-gname">light house</span>
</div>
<div class="list">
</div>
<div class="list">
</div>
<div class="list">
</div>

Short HTML Code from Json will display the HTML code instead of the rendered version

I'm retrieving an array filled with user data. They should be displayed in a ul. One of the fields is the prefix for every user as an html code like this <span class="red-text">[Admin]</span>. But when I try to append the li element it renders the html code instead of the red version of the span.
My json code:
{
"users":[
{
"id":"1",
"usrname":"YannickFelix",
"email":"example#gmail.com",
"lvl":"4",
"prefix":"<span class=\"red-text\">[Admin]<\/span>"
}
]
}
And my javascript:
listElemTmplt = `
<li class="collection-item avatar">
<i class="material-icons circle {"{{color}}"}">person</i>
<span class="title">{"{{usrname}}"}</span>
<p>{"{{prefix}}"} {"{{usrname}}"} | {"{{email}}"}
</p>
<span class="secondary-content">
<a class="waves-effect waves-circle" href="users.php?action=edit&uID={"{{id}}"}">
<i class="material-icons grey-text text-darken-1">create</i>
</a>
<a class="waves-effect waves-circle waves-red modal-trigger" href="#modal{"{{id}}"}">
<i class="material-icons grey-text text-darken-1">delete</i>
</a>
</span>
<div id="modal{"{{id}}"}" class="modal">
<div class="modal-content black-text">
<h4>Löschen</h4>
<p>Möchtest Du den Benutzer "{"{{usrname}}"}" wirklich löschen?</p>
</div>
<div class="modal-footer">
Abbrechen
Löschen
</div>
</div>
</li>
`;
template = Handlebars.compile(listElemTmplt);
finishedString = [];
$.getJSON("**url**", function (data) {
console.log(data);
$("ul#users").html("");
data["users"].forEach(function (element, index, array) {
html = template({"{"}id: element["id"], usrname: element["usrname"], email: element["email"], prefix: element["prefix"]{"}"});
$("ul#users").append(html);
});
});
The example item in the List. [Admin] should be red and without the html code
Handlebars escapes the values you give to it when using {{prefix}}. When you want to use raw HTML you have to use {{{prefix}}} to tell it not to escape it.

How to hide an element based on another existing

I have a jQuery code that looks for a specific div element.
If the element exist I define a variable and use parseFloat() function. Since there are going to be more than one element with the same class I've created an array.
So far I've managed to hide the element called: div.ifc-balance-div; however I am not quite sure how I can hide the div.ribbon-yellow, in case the element does not have the variable savePrice.
(function($) {
"use strict";
$(document).ready(function() {
var j = 0,
savePrices = jQuery('.special-price .price .price').map(function() {
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
if(j < savePrices.length){
++j;
}
for (var i = 0; i < savePrices.length; ++i) {
if (Number(savePrices[i]) > 0) {
var ifcBalance = Number(savePrices[i]) / 1,
m = parseFloat(ifcBalance).toFixed(0);
$('div.ifc-balance-div' + (i + 1)).html('<p class="dynamic-badge-txt"><b>£' + m + ' OFF</b></p>');
$('div.ribbon-yellow').html('<div class="badge-ends-message">ENDS TUESDAY</div>');
}
else {
$('div.ifc-balance-div' + (i + 1)).hide();
}
}
});
})(jQuery);
Here is a sample of the HTML Code:
one having Save Price:
Text
<div class="price-box">
<p class="old-price">
<span class="price-label">Was</span>
<span class="price" id="old-price-15510">
<span class="price"><span class="currency">£</span>599</span> </span>
</p>
<p class="special-price">
<span class="price-label">You Save</span>
<span class="price" id="price-excluding-tax-15510">
<span class="price"><span class="currency">£</span>300</span> </span>
</p>
</div>
From
£299
One without save price:
<div class="ribbon-yellow"></div>
<div>
</div></div></div>
<a href="#" title="#">
<img src="#" alt="#">
</a>
</div>
<div class="item__detail">
<a href="#" title="#" class="item__link">
<p class="product-name item__name">Text</p>
</a>
<div class="price-range">
<span class="price-label">From </span>
<span class="price"><span class="price"><span class="currency">£</span>299</span></span>
</div>
</div>
</div>

Categories