I'm working on a Laravel project where user can favorite and unfavorite books, in the two cases the DB changes successfully without page reloading as i used ajax , but i have two problems:
-first problem : if there is no favorite books, favorite button disappears and i need to edit database to add some book to favorites table and show the button again.
- second problem is that when more than one book is favorited when i refresh the page, the favorite button is duplicated .
here is the code in my controller:
class FavoriteController extends Controller
{
public function bookFavBook(Request $request){
$book_id = $request['bookid'];
$fav = DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->first();
check if books fav or unfav
if(!$fav){
$newfav = new Favorite;
$newfav->book_id =$book_id;
$newfav->user_id = Auth::user()->id;
$newfav->fav = 1;
$newfav->save();
to use in ajax
$is_fav = 1;
}
elseif ($fav->fav == 1){
DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->delete();
$is_fav = 0;
}
elseif ($fav->fav == 0){
DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->update(['fav'=> 1] );
$is_fav = 1;
}
$response = array(
'is_fav'=>$is_fav,
);
return response()->json($response, 200);
}
and the code in my view :
first loop
#foreach( $books as $book)
<div class="container-fluid column">
<div class="row flex-row flex-nowrap">
<div class="col-md-4">
<div class="card card-block">
<div>
<img
class="card-img-top"
src="/images/{{ $book-> book_img}}"
alt="Card image cap"
/>
</div>
<h5 class="card-title"> {{ $book ->title}} </h5>
<p class="card-text">
{{ $book-> description}}
</p>
<div class="card">
<div class="mb-3">
<span class="badge badge-pill badge-primary p-2 mr-4">
<span class="count_of_book">{{ $book-> amount }}</span>
copies available
</span>
query books from favorites table
#php
$getbook = DB::table('books')
->join('favorites','favorites.book_id','=', 'books.id' )
->where('favorites.user_id','=',Auth::id())
->get();
#endphp
socond loop
#foreach($getbook as $fbook)
**#if($fbook->book_id == $book->id )
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-danger"></i>
#else
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-dark"></i>
#endif**
end second loop
#endforeach
</div>
</div>
end first loop
#endforeach
</div>
{{ $books->links() }}
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var token = '{{ Session::token()}}';
var urlFav = '{{ route('favor') }}';
</script>
and the ajax code in js file:
$(".fa-heart").on("click", function (event){
bookid = $(this).data("bookid");
$.ajax({
method: 'POST',
url: urlFav,
data: {bookid: bookid , _token:token},
success: function(data){
if(data.is_fav == 1){
$(event.target).removeClass("text-dark").addClass("text-danger");
}
if(data.is_fav == 0){
$(event.target).removeClass("text-danger").addClass("text-dark");
}
}
});[show duplication of the buuton][1]
[1]: https://i.stack.imgur.com/551I4.png
Don't perform a join query, instead fetch books first then inside your for loop check whether the books are present in the favorite table . If they are present and are favorite than show that they are favorite else show that they are not favorite.
#php
$getbook = DB::table('books')->get();
#endphp
#foreach($getbook as $fbook)
#php
$fav = DB::table('favorites')->where(['book_id' => $fbook->id])->get();
#endphp
#if($fav != null && $fav->is_fav == 1)
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-danger"></i>
#else
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x text-dark"></i>
#endif
#endforeach
Related
I've got a pretty straight forward setup.
Trying to display a list of users with a search box at the top (for actively filtering the search results).
If I use just that the page works and displays fine.
I'm trying to add in an additional dropdown to pick an attribute to sort by (and hopefully add in another dropdown to indicate ascending/descending once I get the first dropdown working).
My current code (with a non-working version of the sort) looks like this:
<div id="app">
<section class="mb-3">
<div class="container">
<h2>Person Search</h2>
<h3>
<small class="text-muted">Filter people based on the name, location or job</small>
</h3>
<h3>
<small class="text-muted">
Examples: “Jane Doe”, “ABC Building”, or “Math”
</small>
</h3>
<input type="text" class="form-control" v-model="search_term" placeholder="Begin typing to filter by name, location or job...">
<!-- THIS WOULD CAUSE THE LIST TO FILTER ALPHABETICALLY BY SELECTED ATTRIBUTE -->
<select id="sortFilterSelect" name="sort_filter" v-model="sort_filter">
<option value="">Sort By...</option>
<option value="first_name">First Name</option>
<option value="last_name">Last Name</option>
</select>
</div>
</section>
<section>
<div class="container">
<h3>People List : ([[ people_count ]] People)</h3>
<!-- I ADDED 'sortedPeople' HERE - WHICH BROKE IT -->
<div v-for="person in filteredPeople | sortedPeople">
<div class="card mb-4" :class="person.has_summative_past_due ? 'alert-warning' : ''">
<div class="card-body row" >
<div class="col">
<h4 class="card-title" v-bind:person='person.full_name'><a v-bind:href="'{% url 'commonground:index' %}' + 'users/' + person.id">[[ person.full_name ]]</a></h4>
<p v-if="person.active_summative" class="card-text">
Active Summative Due Date: [[ person.active_summative.due_date ]]
<span v-show="!person.active_summative.past_due" v-bind:past_due='person.active_summative.past_due' class="badge badge-success">[[ person.active_summative.due_date_status ]]</span>
<span v-show="person.active_summative.past_due" class="badge badge-danger">[[ person.active_summative.due_date_status ]]</span>
<ul class="list-group list-group-flush">
<li class="list-group-item justify-content-between align-items-center" v-for="summary in person.summative_evaluations_summary">
<span class="badge badge-secondary badge-pill">[[summary.evaluation_type__count]]</span> [[ summary.evaluation_type__name ]]
</li>
</ul>
</p>
<p v-if="!person.active_summative" class="card-text">
No Active Unlocked Summatives
</p>
<a v-if="person.active_summative" :href="person.active_summative.absolute_url" class="btn btn-primary"><i class="far fa-edit"></i> View / Edit Active Summative</a>
</div>
<div class="col-auto float-right text-right">
<p class="h5">
[[ person.base_location ]]
<div v-if="person.multiple_locations" class="small text-muted"><i class="fal fa-info-circle"></i> User has multiple locations</div>
</p>
<p class="h5">
[[ person.assignment_job ]]
<div v-if="person.multiple_jobs" class="small text-muted"> <i class="fal fa-info-circle"></i> User has multiple jobs</div>
</p>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- END OF VUE -->
</div>
The actual Vue code looks like this:
<script>
const app = new Vue({
delimiters: ['[[', ']]'],
el: '#app',
data: {
people: [],
people_count: 0,
search_term: "",
sort_filter: "",
},
computed: {
filteredPeople:function()
{
var search = this.search_term.toLowerCase();
return this.people.filter(function(person){
return Object.values(person).some( val => String(val).toLowerCase().includes(search))
})
},
sortedPeople:function()
{
var sort_filter = this.sort_filter.toLowerCase();
console.log('triggered')
return this.people.filter(function(person){
return Object.values(person).some( val => String(val).toLowerCase().includes(sort_filter))
})
},
},
async created () {
var response = await fetch("{% url 'user-list' %}");
this.people = await response.json();
this.people_count = await this.people.length
}
})
</script>
Fairly new to Vue, but I am building this to learn. All help is appreciated!
Check out the simple sample I made: Link
filteredPeople() {
return this.people.filter(
(person) =>
person.firstname
.toLowerCase()
.includes(this.search.toLowerCase().trim()) ||
person.lastname
.toLowerCase()
.includes(this.search.toLowerCase().trim())
);
},
sortedPeople() {
return this.filteredPeople.sort((a, b) =>
a[this.sortby].localeCompare(b[this.sortby])
);
},
Added asc/dec order: Link
sortedPeople() {
return this.filteredPeople.sort((a, b) =>
(this.sort == 'asc') ? a[this.sortby].localeCompare(b[this.sortby]) : b[this.sortby].localeCompare(a[this.sortby])
);
},
I am currently working on ajax, jquery and javascript. I have slight problems with it.
I can use this code to send the data and they are stored in the database.
But the data will not be displayed directly after sending in the view, until I have reloaded the page.
How can I output the data directly in the view without reloading the page?
How can I output errors and success messages as flashmessage (toastr) message?
how can I rewrite this code that works? I get the error message that it is a duplicate of the selectors.
$('#todolist-create-modal').modal('hide');
$('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
Code
<script type="application/javascript">
$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#add-todo-list').click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val(); // get csrf field.
var title = $("input[name='title']").val();
var description = $("textarea[name='description']").val();
var privacy = $("select[name='privacy']").val();
var listid = $("select[name='privcy']").val();
$.ajax({
url:'{{ route('todolists.store') }}',
type: 'POST',
data: {_token:_token, title:title, description:description, privacy:privacy},
success: function (data) {
console.log(data);
if (privacy = 0) {
//go to the left side
} else {
//go to the right side
}
},
error: function(data){
console.log(data);
}
});
$('#todolist-create-modal').modal('hide');
$('#todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
});
});
</script>
view
<div id="content" class="dashboard padding-10">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<a data-toggle="modal" data-target=".todolist-create-modal" class="btn btn-success btn-block btn-sm margin-bottom-10">Neue Liste erstellen</a>
</div>
<div class="col-md-6">
<div id="panel-misc-portlet-l3" class="panel panel-default text-center">
<div class="panel-heading nohover">
<span class="elipsis">
<strong>Öffentliche Tasks</strong>
</span>
</div>
</div>
<div class="alert alert-danger margin-bottom-30 {{ $todolistpublic->count() ? 'hidden' : '' }}">
Es wurden keine <strong>Einträge</strong> gefunden.
</div>
#foreach ($todolistpublic as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden">
<i class="fa fa-plus"></i> Erstellen
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-info btn-xs white hover-hidden">
<i class="fa fa-edit"></i> Bearbeiten
</a>
</li>
<li><a data-toggle="modal" data-target=".todolist-delete-modal" data-id="{{ $list->id }}" data-title="{{ $list->title }}" data-description="{{ $list->description }}" class="btn btn-danger btn-xs white hover-hidden">
<i class="fa fa-times"></i> Löschen
</a>
</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
<div class="panel-footer mtm-10">
<span id="todo-list-counter-public">{{ $todolistpublic->count() }}</span> <span>{{ $todolistpublic->count() > 1? 'Listen' : 'Liste' }}</span>
</div>
</div>
<div class="col-md-6">
<div id="panel-misc-portlet-l3" class="panel panel-default text-center">
<div class="panel-heading nohover">
<span class="elipsis">
<strong>Private Tasks</strong>
</span>
</div>
</div>
<div class="alert alert-danger margin-bottom-30 {{ $todolistprivate->count() ? 'hidden' : '' }}">
Es wurden keine <strong>Einträge</strong> gefunden.
</div>
#foreach ($todolistprivate as $list)
<div id="todo-list-{{$list->id}}" class="panel panel-default panel-primary margin-bottom-0">
<div class="panel-heading panel-pointer">
<span class="elipsis"><!-- panel title -->
<strong>{{ $list->title }}</strong> <span class="label label-info white">0</span>
</span>
<ul class="options pull-right relative list-unstyled hover-visible">
<li><a data-toggle="modal" data-target=".task-modal" class="btn btn-success btn-xs white hover-hidden"><i class="fa fa-plus"></i> Erstellen</a></li>
<li><a data-toggle="modal" data-target=".todolist-modal" class="btn btn-info btn-xs white hover-hidden"><i class="fa fa-edit"></i> Bearbeiten</a></li>
<li><i class="fa fa-times"></i> Löschen</li>
<li></li>
</ul>
</div>
<div class="panel-body">
<div class="slimscroll" data-always-visible="false" data-rail-visible="false" data-railOpacity="1" data-height="100">
{{ $list->description }}
</div>
</div>
</div>
#endforeach
<div class="panel-footer mtm-10">
<span id="todo-list-counter-private">{{ $todolistprivate->count() }}</span> <span>{{ $todolistprivate->count() > 1? 'Listen' : 'Liste' }}</span>
</div>
</div>
#include('elements.addTodoList')
#include('elements.createTodoList')
#include('elements.addTask')
</div>
</div>
Controller
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|min:5',
'description' => 'required|min:10',
'privacy' => 'required|integer'
]);
$attributeNames = array(
'title' => 'Title',
'description' => 'Description',
);
$validator->setAttributeNames($attributeNames);
//Redirect back if validation fails
if($validator->fails()) {
return response()->json(['error'=>$validator->errors()->all()]);
}
else{
$todolists = new Todolists();
$todolists->admin_id = Auth::id();
$todolists->title = $request->title;
$todolists->description = $request->description;
$todolists->privacy = $request->privacy;
$todolists->save();
return response()->json(['Your enquiry has been successfully submitted!']);
}
}
EDIT
I have revised and adapted the code. Currently I have two more problems:
The flashmessage is only output as 'empty'. Without text content. Where is the problem?
The div is also reloaded. But after it was loaded I can not send the same request again. Do I have to reset something or what is the error?
When I issue the errors in the console with console.log(data); I get the following error messages:
{error: Array(2)}
error
:
(2) ["The Title ist erforderlich.", "The Description ist erforderlich."]
<script type="application/javascript">
$(document).ready(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('#add-todo-list').click(function(e) {
e.preventDefault();
$('.todolist-create-modal').on('keypress', ":input:not(textarea)", function(event) {
return event.keyCode != 13;
});
var _token = $("input[name='_token']").val(); // get csrf field.
var title = $("input[name='title']").val();
var description = $("textarea[name='description']").val();
var privacy = $("select[name='privacy']").val();
$.ajax({
url:'{{ route('todolists.store') }}',
type: 'POST',
data: {_token:_token, title:title, description:description, privacy:privacy},
success: function (response) {
if (response.error) {
_toastr((response),"top-full-width","error",false);
}
else{
$('.todolist-create-modal').modal('hide');
$("#content").load(location.href+" #content>*","");
_toastr((response),"top-full-width","success",false);
}
}
});
});
});
</script>
Q: How can I output the data directly in the view without reloading the page?
One way with jQuery was loading partial content, this will request again the page, get the contents of #content div and replace the HTML, fast and without reload the page:
$("#content").load("/url-of-page > #content > *");
Q: How can I output errors and success messages as flashmessage (toastr) message?
Just write the message on a HTML element:
success: function(data){
$(".alert-danger").addClass("hidden");
$(".alert-success").html(data.msg).removeClass("hidden");
},
error: function(data){
$(".alert-success").addClass("hidden");
$(".alert-danger").html(data.error).removeClass("hidden");
}
I'm working on a system where the user can select a product and go to the next page. This product then gets saved in the session using laravel sessions. When the user decides to go to the next page and come back. The chosen product is indeed saved in the session, but the is no way for them to see what product they have chosen because the class isn't applied to the product that was chosen.
The code may clarify it better:
#foreach($themes as $theme)
<div class="col-md-4 mb-4">
<div class="card theme-card card-hover depth-2 border-0" id="theme-id-{{$theme->id}}">
<a href="" class="theme-link" data-toggle="modal" data-target="#theme{{ $theme->id }}">
<div class="card-image" style="height: 200px; background-image: url('/uploads/{{ $theme->thumbnail }}'); background-size: cover; background-position: center center;"></div>
<div class="card-body">
<div class="row">
<div class="col-md-2 vertical-center">
<i class="fab fa-magento fa-lg"></i>
</div>
<div class="col-md-10">
<p class="m-0">{!! str_limit($theme->name, $limit = 32, $end = '...') !!}</p>
<small class="text-muted">{{ $theme->productable_type }}</small>
</div>
</div>
</div>
</a>
<div class="card-footer bg-white border-0 text-right pt-0">
<div class="row">
<div class="col-md-6 text-left">
<input type="hidden" class="theme-name" name="theme[{{$theme->id}}]">
{{--<input type="hidden" value="{{ $theme->composer_package }}">--}}
<button data-card-id="{{$theme->id}}" class="btn btn-orange btn-sm btn-theme-choice">Kiezen</button>
</div>
<div class="col-md-6 text-right">
<span style="font-size: 20px;" >€ {{ $theme->price }} EUR</span>
</div>
</div>
</div>
</div>
</div>
#endforeach
In the above code, I for each trough every so-called "Theme" and I'm giving the ID of the theme as a data target and as ID. Then in my Javascript code, I do the following:
$('.btn-theme-choice').on('click', function (event) {
event.preventDefault();
newSelectedCardId = $(event.target).data('card-id');
if(cardId === null) {
cardId = newSelectedCardId;
} else if (cardId !== newSelectedCardId) {
$('#theme-id-' + cardId).removeClass('theme-chosen').find("input[name='theme["+cardId+"]']").val('');
cardId = null;
}
var card = $('#theme-id-' + cardId );
card.toggleClass('theme-chosen');
selectedCardInput = card.find("input[name='theme["+cardId+"]']");
if( !$('.theme-card').hasClass('theme-chosen') ) {
selectedCardInput.val('');
} else if ( $('.theme-card').hasClass('theme-chosen') ) {
selectedCardInput.val('selected');
}
console.log(selectedCardInput);
});
Here I add the class to the card so the user can See which card they've selected. This choice then gets saved in the session using some PHP code in the controller
if( $theme == null ) {
return redirect('plugins');
} elseif( $theme != null ) {
foreach($this->predefinedArray as $value) {
$request->session()->put('chosen_theme.' . $value, $theme->$value);
}
$request->session()->put('chosen_theme.composer_package', $theme->productable->composer_package);
return redirect('plugins');
}
problem
How can I read the session and add the class to the card with the IDs that were stored in the session so if the person leaves the page and comes back, they can see what cards they've selected?
Thanks in advance
Try this in your view..
<div class="card theme-card card-hover depth-2 border-0 {{ \Session::get('chosen_theme.composer_package') == $theme->id ? 'theme-chosen' : '' }}" id="theme-id-{{$theme->id}}">
Whenever the theme id is in the session and the page loaded the class will be added, and if it is not in the session then the class won't be added.
Let me know the result..
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).
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)">