I'm using this code to show images.
The problem is that it is showing popup only for the first image and not the rest.
Images are loaded from database so they all have the same id.
Is that the problem or something else?
Code :
if (ViewBag.ReceptiSearchAll != null)
{
<div class="col-6 col-lg">
#foreach (var images in ViewBag.ReceptiSearchImages)
{
if (images.Image != null)
{
imagePath = images.Image;
}
else
{
imagePath = images.ImageDefault;
}
<div class="card mb-3" style="max-width: 400px;border:none">
<div class="row no-gutters">
<div class="col-md-12">
<img id="imgrec" class="card-img-top" src="data:image;base64,#System.Convert.ToBase64String(imagePath)" alt="Slika recepta" width="250" height="200">
</div>
</div>
</div>
}
</div>
}
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("imgrec");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
</script>
All your images have the same id.
<img id="imgrec" ...
id is meant to be a unique identifier.
var img = document.getElementById("imgrec");
For that reason, only your first image gets this.
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
Related
So here I want to get the latest data from dbs after uploading a image. with reloading the whole page again. Instead I want only to refresh the image div to show the latest uploaded image. I guess we can use Ajax for this, but I don't have any expertise in ajax so anyone who can help will be glad.
Thank you :)
Here is my code :-----------
.cshtml file
#for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
<li class="list-group-item">
<input asp-for="#Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
<label asp-for="#Model.DailyMenuProducts[i].ProductId"> #Model.DailyMenuProducts[i].ProductName</label>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductId"/>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
#if(#Model.DailyMenuProducts[i].DisplayImage != null)
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<label class="file-label">
<img src="data:image/jpeg;base64,#Model.DailyMenuProducts[i].DisplayImage" width="80" height="80" style="border: 1px solid #000000; cursor:pointer;"/>
</label>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div> }
else
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<a class="file-label btn btn-primary text-white" type="button">
#SharedLocalizer[CashlessCloudConstants.cacheKey_UploadImage]
</a>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div>
}
</li>
}
.js file
$(".file-label").click(function () {
var parent = $(this).parent();
var target = $(parent).find(".productImage");
$(target).click();
});
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
var imagefiles = event.target.files;
var id = event.target.id;
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(imagefiles[0]));
var formData = new FormData();
formData.append("productId", id);
formData.append("productImage", imagefiles[0]);
console.log(formData.getAll("productId"));
console.log(formData.getAll("productImage"));
console.log(imagefiles[0])
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
contentType: false,
processData: false,
data: formData,
method: "POST",
success: function (result) {
window.onbeforeunload = null;
location.reload();
}
});
});
.cs file [Controller Method for AddPhoto]
[HttpPost]
public async Task<IActionResult> AddPhoto([FromForm] DailySelectedProductViewModel dataModel)
{
var userSession = await _userSessionCache.GetUserSessionWithUserIdAsync();
if (dataModel == null)
{
return View("ProductSelection", dataModel);
}
var existing = await _productImageApiService.GetSingleProductImage(userSession.TenantId,dataModel.ProductId);
ProductImages productImage = new ProductImages();
HttpRequest request = HttpContext.Request;
IFormFile file = dataModel.ProductImage;
if (file.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
productImage.ProductImage = imageAsArray;
}
productImage.ProductId = dataModel.ProductId;
}
if (existing.Content != null)
{
await _productImageApiService.Delete(userSession.TenantId,dataModel.ProductId);
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
else
{
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
return Ok();
}
I want to make tab switcher auto decide the slot for the switcher but when I am trying to make it dynamic with the help of observable no data is showing the tab content area until I write the slot area statically. With observable variable, the slot is not getting the selected Slot value.
Please check how I can do this.
slot = [[selectedSlot]] //using for the slot value in html
this.selectedSlot = ko.observable('settings');
<div id="tabbardemo">
<oj-dialog class="tab-dialog hidden" id="tabDialog" dialog-title="Tab data">
<div slot="body">
<oj-form-layout>
<oj-input-text id="t1" value="{{newTabTitle}}" label-hint="Title"></oj-input-text>
</oj-form-layout>
</div>
<div slot="footer">
<oj-button id="idOK" on-oj-action="[[addTab]]">OK</oj-button>
<oj-button id="idCancel" on-oj-action="[[closeDialog]]">Cancel</oj-button>
</div>
</oj-dialog>
<oj-button id="addTab" on-oj-action="[[openDialog]]">Add Tab</oj-button>
<br/>
<br/>
<oj-tab-bar contextmenu="tabmenu" id="hnavlist" selection="{{selectedItem}}" current-item="{{currentItem}}" edge="top" data="[[dataProvider]]"
on-oj-remove="[[onRemove]]">
<template slot="itemTemplate" data-oj-as="item">
<li class="oj-removable" :class="[[{'oj-disabled' : item.data.disabled}]]">
<a href="#">
<oj-bind-text value="[[item.data.name]]"></oj-bind-text>
</a>
</li>
</template>
<oj-menu slot="contextMenu" class="hidden" aria-label="Actions">
<oj-option data-oj-command="oj-tabbar-remove">
Removable
</oj-option>
</oj-menu>
</oj-tab-bar>
<oj-switcher value="[[selectedItem]]">
<div slot="[[selectedSlot]]"
id="home-tab-panel"
role="tabpanel"
aria-labelledby="home-tab">
<div class="demo-tab-content-style">
<h2>Home page content area</h2>
</div>
</div>
<div slot="tools"
id="tools-tab-panel"
role="tabpanel"
aria-labelledby="tools-tab">
<div class="demo-tab-content-style">
<h1>Tools Area</h1>
</div>
</div>
<div slot="base"
id="base-tab-panel"
role="tabpanel"
aria-labelledby="ba`enter code here`se-tab">
<div class="demo-tab-content-style">
<h1>Base Tab</h1>
</div>
</div>
</oj-switcher>
<br>
<div>
<p class="bold">Last selected list item:
<span id="results">
<oj-bind-text value="[[selectedItem]]"></oj-bind-text>
</span>
</p>
</div>
</div>
JS code below
require(['ojs/ojcontext',
'knockout',
'ojs/ojbootstrap',
'ojs/ojarraydataprovider',
'ojs/ojknockout',
'ojs/ojnavigationlist',
'ojs/ojconveyorbelt',
'ojs/ojdialog',
'ojs/ojbutton',
'ojs/ojinputtext',
'ojs/ojformlayout',
'ojs/ojswitcher',
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
this.data = ko.observableArray([{
name: 'Settings',
id: 'settings'
},
{
name: 'Tools',
id: 'tools'
},
{
name: 'Base',
id: 'base'
}
]);
this.selectedSlot = ko.observable('settings'); //Sepecifically mentioned to show what it is the objective
this.dataProvider = new ArrayDataProvider(this.data, { keyAttributes: 'id' });
this.selectedItem = ko.observable('settings');
this.currentItem = ko.observable();
this.tabCount = 0;
this.newTabTitle = ko.observable();
this.delete = (function (id) {
var hnavlist = document.getElementById('hnavlist');
var items = this.data();
for (var i = 0; i < items.length; i++) {
if (items[i].id === id) {
this.data.splice(i, 1);
Context.getContext(hnavlist)
.getBusyContext()
.whenReady()
.then(function () {
hnavlist.focus();
});
break;
}
}
}).bind(this);
this.onRemove = (function (event) {
this.delete(event.detail.key);
event.preventDefault();
event.stopPropagation();
}).bind(this);
this.openDialog = (function () {
this.tabCount += 1;
this.newTabTitle('Tab ' + this.tabCount);
document.getElementById('tabDialog').open();
}).bind(this);
this.closeDialog = function () {
document.getElementById('tabDialog').close();
};
this.addTab = (function () {
var title = this.newTabTitle();
var tabid = 'tid' + this.tabCount;
this.data.push({
name: title,
id: tabid
});
this.closeDialog();
}).bind(this);
}
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
}
);
It is a bit complex to understand when you copy from JET cookbook. You have done almost everything right. Just make the following changes:
1) Remove this:
Bootstrap.whenDocumentReady().then(function () {
ko.applyBindings(new ViewModel(), document.getElementById('tabbardemo'));
});
Why? The bootstrapping is required once per application, which is done inside your main.js file.
2) Replace require by define
Why? Require block is again maintained in main.js, where your required modules are pre-loaded. All subsequent viewModels have define block
3) Return an instance of your ViewModel
define([
... Your imports
],
function (Context, ko, Bootstrap, ArrayDataProvider) { // this callback gets executed when all required modules are loaded
function ViewModel() {
// Your code
}
return ViewModel;
});
I have to display a delete icon (png file) when the user upload a picture.
I use the following code for display the picture
$(document).ready(function(){
var $file = $('input[type=file]');
$('a.ui-icon-camera').click(function () {
$file.trigger("click");
});
$file.change(function () {
var file = $file[0].files[0];
$(this).fileExif(someCallback);
displayAsImage3(file,"showPic");
});
});
function displayAsImage3(file, containerid) {
if (typeof FileReader !== "undefined") {
var container = document.getElementById(containerid),
img = document.createElement("img"),
reader;
$(img).addClass('smallImg');
$('#'+containerid).empty();
container.appendChild(img);
reader = new FileReader();
reader.onload = (function (theImg) {
return function (evt) {
theImg.src = evt.target.result;
};
}(img));
reader.readAsDataURL(file);
}
}
<div class="hiddenfile"><input type="file" name=${pictureName} accept="image/*" /></div>
<div id="showPic" style="background-color: #E5E5E5; margin: -7% 0; margin-bottom: 1px ">
</div>
How can I append to the image the png icon?
i´m running into a problem with hammer an it´s tap event.
I´m using this script to display an hidden div on tap event.
Inside of this div construct, i have an a tag with an link, but it break apart, and i don´t know why.
<div id="_news_8_" class="news_latest small-12 medium-6 columns">
<div class="news-info">
<div class="news-info-content table tap-object">
<div class="table-cell align-middle">
<h2>Headline</h2>
<h6>Subheadline</h6>
<p class="more">> Detail <span class="invisible">Text</span></p>
</div>
</div>
</div>
<div id="_slidesnews_8_" class="_bstretch_">
...
</div>
</div>
and the script
$tapObject = $('.tap-object');
[].slice.call($tapObject).forEach(function(element) {
hammertap = new Hammer(element);
hammertap.on('tap', function(event) {
if (event.target !== activeTap) {
if (activeTap !== undefined) {
$(activeTap).removeClass('on');
}
$(event.target).addClass('on');
}
activeTap = event.target;
});
});
so what´s going wrong here?
here´s a live demo: http://holmgallery.com/index.php/collection.html
Down under the Header Gallery, tap on one of the objects
Ok, Got it - so using the jQuery Wrapper Plugin, give´s me more Control over Delegation. Now the a.href work´s as it should.
var $rootObject = $('.news_latest');
[].slice.call($rootObject).forEach(function(element) {
hammertap = new Hammer(element);
$(element).hammer({domEvents:true}).on("tap", '.tap-object', function(event) {
if (event.currentTarget !== lastTap) {
if (lastTap !== undefined) {
$(lastTap).removeClass('on');
}
$(event.currentTarget).addClass('on');
lastTap = event.currentTarget;
}
});
});
I'm trying to set a listview like that:
http://jquerymobile.com/demos/1.2.0/docs/lists/lists-thumbnails.html
I dinamicly generate my code
$('#calendarPage').live('pagebeforeshow', function(event) {
$('#calendarPage').live('pageshow', function(event) {
application.prev = 'menu.html';
//get the actu
application.readFile('calendar.json',function(data){
data = JSON.parse(data);
var listview = '<ul data-role="listview" class="ui-listview" id="calendarList" >';
for(elem in data){
var date = new Date(data[elem].date);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getYear();
var hours = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
listview += '<li>';
listview += '<img src="'+application.api+data[elem].img+'" /><a href="actuOne.html?id='+elem+'" ><h3>'+data[elem].title+'</h3><p>'+day+'/'+month+'/'+year+' '+hours+':'+min+':'+s+'</p></a>';
listview += '</li>';
}
listview += '</ul>';
$('#calendarPage .content').html(listview);
$('#calendarList').listview();
});
});
});
Yhe listview is created but the images are not resized
I try adding class="ui-li-thumb" but it works poorly
Thanks
There's an error in your example, img tag must be inside a a tag, only then it will be resized.
Take a look at this example: http://jsfiddle.net/Gajotres/w5bcS/
<ul data-role="listview">
<li><a href="index.html">
<img src="http://www.warrenphotographic.co.uk/photography/bigs/05852-Retriever-puppy-yawning-white-background.jpg" title="sample"/>
<h3>Sample image</h3>
<p>Sample</p>
</a></li>
<li><a href="index.html">
<img src="http://www.warrenphotographic.co.uk/photography/bigs/05852-Retriever-puppy-yawning-white-background.jpg" title="sample"/>
<h3>Sample image</h3>
<p>Sample 2</p>
</a></li>
</ul>