how to send 2 parameters from Javascript to controller - javascript

This might be a silly question...
In my website I have 3 types of images: TYPE A, TYPE B and TYPE C.
All images, no matter what type they are, if you click on them, it opens a lightbox as modal carrousel, and each image you could download them individually.
What's the problem? The problem is that each type of image are in different tables in a db, so I have 3 differents paths to search:
TYPE A images are in TABLE A
TYPE B images are in TABLE B
TYPE C images are in TABLE C
So, how can I send from Javascript, from the button Download Image, the type of image I'm actually showing? What I can do is to send the src of the image, but not the TYPE
The TYPE of each image is assigned by a name in each image:
<img alt="Image" class="imgPedido" id="#cont" src="#pd.getImagenes()" data-img-mostrar="#cont" name="A"/>
<img alt="Image" class="imgPedido" id="#cont" src="#pd.getImagenes()" data-img-mostrar="#cont" name="B"/>
<img alt="Image" class="imgPedido" id="#cont" src="#pd.getImagenes()" data-img-mostrar="#cont" name="C"/>
What I tried is to have a function where it receives the src (imageSelec) of the image selected and ask if A, B or C is null or empty:
public void DownloadImagen(string imageSelec, string A, string B, string C)
{
try
{
Logger.Debug("IMAGE SELECTED ---> " + imagenSelec);
Logger.Debug("IMAGE A ---> " + A);
Logger.Debug("IMAGE B ---> " + B);
Logger.Debug("IMAGE C ---> " + C);
if (A!= null || A!= "")
{
DownloadImageA(imagenSelec);
}
else if (B!= null || B!= "")
{
DownloadImageB(imagenSelec);
}
else if (C != null || C != "")
{
DownloadImageC(imagenSelec);
}
}
catch (Exception ex)
{
Logger.Error(ex.Message + " || Funcion: DescargarImagen()");
ViewData["ERROR"] = ex.Message;
throw new Exception(ex.Message);
}
}
I used Loggers to see what the function recieves and this is the result:
In this case it should be image A:
Here is my lightbox:
const galleryItem = document.getElementsByClassName("gallery-item");
const lightBoxContainer = document.createElement("div");
const lightBoxContent = document.createElement("div");
const lightBoxImg = document.createElement("img");
const lightBoxPrev = document.createElement("div");
const lightBoxNext = document.createElement("div");
const btnDownload = document.createElement("button");
const closeBtn = document.createElement("button");
const form = document.createElement("form");
const divBtnX = document.createElement("div")
const body = document.getElementById("bodyId")
const imgBtnDownload = document.createElement("img");
imgBtnDownload.setAttribute("src", "/Img/descargas.png");
imgBtnDownload.setAttribute("id", "imgBtnDownload")
imgBtnDownload.setAttribute("class", "mx-1")
form.setAttribute("action", "/Home/DownloadImagen");
form.setAttribute("class", "mb-3 position-relative")
lightBoxContainer.classList.add("lightbox");
lightBoxContent.classList.add("lightbox-content");
lightBoxPrev.classList.add("fa", "fa-angle-left", "lightbox-prev");
lightBoxNext.classList.add("fa", "fa-angle-right", "lightbox-next");
divBtnX.classList.add("d-flex", "justify-content-end")
closeBtn.classList.add("btn-close", "btn-close-white", "mt-4", "mx-4");
closeBtn.setAttribute("type", "button");
closeBtn.setAttribute("onclick", "closeLightBox()")
closeBtn.setAttribute("data-bs-dismiss", "gallery-item")
closeBtn.setAttribute("aria-label", "Close")
closeBtn.setAttribute("id", "btnCerrar")
btnDownload.classList.add("buttons", "btnDescargarImgs", "mt-3");
btnDownload.innerHTML = "Descargar Imágen";
btnDownload.setAttribute("type", "submit")
btnDownload.setAttribute("id", "btnDescargarImagen")
btnDownload.setAttribute("name", "imagenSelec");
btnDownload.appendChild(imgBtnDownload)
divBtnX.appendChild(closeBtn)
lightBoxContainer.appendChild(divBtnX);
lightBoxContent.appendChild(lightBoxPrev);
lightBoxContainer.appendChild(lightBoxContent);
lightBoxContent.appendChild(lightBoxImg);
lightBoxContent.appendChild(lightBoxNext);
form.appendChild(btnDownload);
lightBoxContent.appendChild(form);
document.body.appendChild(lightBoxContainer);
let index = 1;
function showLightBox(n) {
if (n > galleryItem.length) {
index = 1;
} else if (n < 1) {
index = galleryItem.length;
}
let imageLocation = galleryItem[index - 1].children[0].getAttribute("src");
lightBoxImg.setAttribute("src", imageLocation);
btnDownload.setAttribute("src", imageLocation);
btnDownload.setAttribute("value", imageLocation)
body.style.overflow = "hidden";
}
function currentImage() {
lightBoxContainer.style.display = "block";
lightBoxContainer.style.opacity = "1";
let imageIndex = parseInt(this.getAttribute("data-index"));
showLightBox(index = imageIndex);
}
for (let i = 0; i < galleryItem.length; i++) {
galleryItem[i].addEventListener("click", currentImage);
}
function slideImage(n) {
showLightBox(index += n);
}
function prevImage() {
slideImage(-1);
}
function nextImage() {
slideImage(1);
}
lightBoxPrev.addEventListener("click", prevImage);
lightBoxNext.addEventListener("click", nextImage);
function closeLightBox() {
body.style.overflow = "auto";
lightBoxContainer.style.display = "none";
}
The functions DownloadImageA, DownloadImageB and DownloadImageC are already done, I used them individually and works fine, so I don't have to change them
So, how can I send the name of the images to the function DownloadImagen?
I hope you understood this..

Related

Change div background image with JavaScript

I have a button that when clicked should change its value, a gif image, and a div background at the same time. I have the value change and gif change working well.
However I'm having trouble changing the div background image. I thought that the code I have below would work, but the carousel__cell change just doesn't change.
I also copied a line of HTML that it would apply to so that you can see the gif is in a completely different div than the carousel__cell. I'm not sure if that is the reason, but I don't know what else to try.
function updateButton(btn, bk, i) {
var front = "../../../.img/sprites/gif-sprites/gen1/";
var temp = "unknown";
var end = document.getElementsByClassName("gif")[i].src;
var length = 9;
var endT = end.substring(end.length - length);
if (btn.value === 'U') {
btn.value = 'S';
temp = "seen";
document.getElementsByClassName("carousel__cell").src = "../../../.img/pokedex/seen.png";
document.getElementsByClassName("gif")[i].src = front + temp + endT;
} else {
if (btn.value === 'S') {
btn.value = 'C';
temp = "caught";
document.getElementsByClassName("carousel__cell").src = "../../../.img/pokedex/caught.png";
document.getElementsByClassName("gif")[i].src = front + temp + endT;
} else {
if (btn.value === 'C') {
btn.value = 'U';
temp = "unknown";
document.getElementsByClassName("carousel__cell").src = "../../../.img/pokedex/unknown.png";
document.getElementsByClassName("gif")[i].src = front + temp + endT;
}
}
}
}
const back = document.querySelectorAll('carousel__cell');
const inputs = document.querySelectorAll('input');
for (let i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('click', () => updateButton(inputs[i], back[i], i));
}
<div class="slideshow-container">
<div class="mySlides"><img class="gif" src="../../../.img/sprites/gif-sprites/gen1/unknown/0001.gif" alt="" onClick="location.href='../../dexentries/0001.html'"></div>
</div>
<div class="carousel">
<div class="carousel__scene">
<ol class="carousel__list">
<li class="carousel__cell"><input type="button" value="U"><img class="sprite" src="../../../.img/sprites/game-sprites/gen1/0001.png" alt="" /><span class="pkmname">Bulbasaur</span></li>
</ol>
</div>
</div>
I was actually able to figure this out after looking a little more. I was able to use jquery to add and remove classes.
$('input').on({
click: function() {
if ($('li.selected input:button').val() == 'S') {
$('li.selected').addClass('seen').removeClass('caught').removeClass('unknown')
}
if ($('li.selected input:button').val() == 'C') {
$('li.selected').addClass('caught').removeClass('unknown').removeClass('seen')
}
if ($('li.selected input:button').val() == 'U') {
$('li.selected').addClass('unknown').removeClass('seen').removeClass('caught')
}
}
})

How can I get my messages to show up properly?

I have two buttons - one that sends two messages with a one-second interval, and the other only sends one message, with the second left as undefined (this will be clearer once you see the code). How do I stop undefined from showing up?
var credits = 0;
var currency = 'Skatter';
function addLog(logBefore, logAfter) {
var par = document.createElement("p");
var node1 = document.createTextNode(logBefore);
var node2 = document.createTextNode(logAfter);
par.appendChild(node1);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 18) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
if (node2 !== undefined) {
setTimeout(function() {
console.log(logBefore)
console.log(logAfter)
var par = document.createElement("p");
var node2 = document.createTextNode(logAfter);
par.appendChild(node2);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 8) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
}, 1000);
}
};
<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' ' + currency)">HUNT</button>
<br>
<button onclick="addLog('Resources sold')">SELL</button>
<div id="logs" style="display: flex; flex-direction: column-reverse;"></div>
On the second button you are passing just one argument to the addLog function.
The core problem with your code is that you are asking if node2 variable you have created is falsey (evaluates to false), but a text node will never evaluate to false because it is an object which holds values
// try this in your browser console
>>> if (document.createTextNode(undefined)) {
console.log("not null")
}
>>> "not null" //output
If you want to check if the program gave a value for the second parameter (logAfter), then you should, explicitly do this instead, like:
if (logAfter !== undefined) {
// do stuff
}
You should change the conditional to check if the direct log logAfter is not undefined, not the textNode. This will fix you issue...
var credits = 0;
var currency = 'Skatter';
function addLog(logBefore, logAfter) {
var par = document.createElement("p");
var node1 = document.createTextNode(logBefore);
var node2 = document.createTextNode(logAfter);
par.appendChild(node1);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 18) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
if (logAfter !== undefined) {
setTimeout(function() {
var par = document.createElement("p");
var node2 = document.createTextNode(logAfter);
par.appendChild(node2);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 8) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
}, 1000);
}
};
<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' ' + currency)">HUNT</button>
<br>
<button onclick="addLog('Resources sold')">SELL</button>
<div id="logs" style="display: flex; flex-direction: column-reverse;"></div>

Function not running after submitting name into prompt

entering correct student name associated with image within prompt but it is not running the "checkAnswer" function
this is the function
function checkAnswer() {
if (document.getElementById('response').value == personArray[currentId].firstname) {
//NOTE TO STUDENT: apply the class to reduce the opacity of the image,
//takeout the mouse events because they shouldn't be there anymore
document.getElementById(currentId).className = "opClass";
document.getElementById(currentId).removeAttribute("onclick");
document.getElementById(currentId).removeAttribute("onmouseover");
//superimpose name on image
var divVar = document.createElement('div');
divVar.setAttribute('id', currentId + 'name');
document.getElementById('pic-grid').appendChild(divVar);
var textNode = document.createTextNode(personArray[currentId].firstname);
divVar.appendChild(textNode);
document.getElementById(currentId + 'name').style.position = "absolute";
document.getElementById(currentId + 'name').style.top = y;
document.getElementById(currentId + 'name').style.left = x;
//clean up loose ends: hide the prompt, turn the frame white so it doesn't change to aqua on the rollover, erase the response and message
document.getElementById('prompt').style.display = 'none';
document.getElementById(currentId).parentNode.style.backgroundColor = 'white';
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
} else {
if (document.getElementById('message').innerHTML == "Wrong!") {
document.getElementById('message').innerHTML = "Incorrect answer!"
} else {
document.getElementById('message').innerHTML = "Wrong!"
}
}
return false;
}
Basically if the user enters the correct name in the prompt that is associated with the image they selected, the image should fade (opacity) and display the name of the student in the image (style position, top, & left) or if they enter the wrong name they are told within the prompt that they are wrong or incorrect.
As soon as I enter the correct student name, the prompt disappears and nothing happens or if I do the wrong name, it disappears as well.
here is the populateImages function that i forgot to place in here, sorry.
function populateImages() {
for (var i = 0; i < personArray.length; i++) {
var imageContainer = document.createElement("div");
var image = document.createElement("img");
imageContainer.classList.add('frame');
image.src = personArray[i].url;
image.setAttribute('onclick','promptForName(this)');
image.setAttribute('onmouseover','styleIt(this)');
image.setAttribute('onmouseout','unStyleIt(this)');
imageContainer.appendChild(image);
document.getElementById('pic-grid').appendChild(imageContainer);
}
}
Here's my HTML:
<body onload="populateImages()">
<header>
<h2>Class Flashcards</h2>
<h3>Click on a student to guess their name</h3>
<h4>Concepts: Rollovers, Opacity, Showing and Hiding Elements, Arrays of Objects, Adding and Removing Elements/Attributes Dynamically to the DOM,
Accessing Elements using parentnode</h4>
</header>
<div id="pic-grid">
</div>
<div id="prompt">
What is this student's name?<br>
<form onsubmit="return checkAnswer()">
<input type="text" id="response" name="quizInput">
</form>
<div id="message"></div>
</div>
</body>
the form is being submitted through this function and shows up when image is selected:
function promptForName(element) {
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
document.getElementById('prompt').style.display = 'block';
currentId = element.id;
x = element.offsetLeft;
y = element.offsetTop;
x = x + 20;
y = y + 20;
document.getElementById('prompt').style.position = "absolute";
document.getElementById('prompt').style.top = y;
document.getElementById('prompt').style.left = x;
document.getElementById('response').focus();
}
return false cancels submit action. you must insert a return true if everything is ok
try this function
function checkAnswer() {
if (document.getElementById('response').value == personArray[currentId].firstname) {
//NOTE TO STUDENT: apply the class to reduce the opacity of the image,
//takeout the mouse events because they shouldn't be there anymore
document.getElementById(currentId).className = "opClass";
document.getElementById(currentId).removeAttribute("onclick");
document.getElementById(currentId).removeAttribute("onmouseover");
//superimpose name on image
var divVar = document.createElement('div');
divVar.setAttribute('id', currentId + 'name');
document.getElementById('pic-grid').appendChild(divVar);
var textNode = document.createTextNode(personArray[currentId].firstname);
divVar.appendChild(textNode);
document.getElementById(currentId + 'name').style.position = "absolute";
document.getElementById(currentId + 'name').style.top = y;
document.getElementById(currentId + 'name').style.left = x;
//clean up loose ends: hide the prompt, turn the frame white so it doesn't change to aqua on the rollover, erase the response and message
document.getElementById('prompt').style.display = 'none';
document.getElementById(currentId).parentNode.style.backgroundColor = 'white';
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
return true; // return true if everything is ok
} else {
if (document.getElementById('message').innerHTML == "Wrong!") {
document.getElementById('message').innerHTML = "Incorrect answer!"
} else {
document.getElementById('message').innerHTML = "Wrong!"
}
return false; // return false if error
}
}

Js & Jquery:Understanding a search code with JSON request

i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>

Text area validation in javascript for html image tag

I want to validate a text area for img tag when it is duplicated. example, if i entered the image tag with src i should enter the same source with tag again i need to show alert how it could be done. my snippet to check whether the image is there or not. but i need to do for above validation also...
function validateEditor() {
var editor_val = $('#asset_html').val(), iSrc;
// Check for empty string
if(!string_IsEmpty(editor_val)) {
// Check whether img is available
if(editor_val.match(/img/g)) {
var src_cnt = (editor_val.match(/img/g).length);
//console.log(editor_val.match(/src/g).length);
$('#asset_html_preview').html(editor_val);
for(var j = 1; j <= src_cnt; j++) {
if($('#asset_html_preview img:nth-child(1)').attr('src')) {
iSrc = $('#asset_html_preview img:nth-child(1)').attr('src');
if(iSrc.indexOf('http://') != -1) {
$('#asset_html_preview img:nth-child(' + j + ')')
.error(function() { alert('Check ur image src'); });
//break;
}
}
}
}
}
}
You may be looking for this:
var arr = {};
var $div = $('<div />').html($('textarea').val());
$div.find('img').each(function (i) {
var src = $(this).attr('src');
if (src.indexOf('http://') >= 0 && arr[src] == undefined) {
arr[src] = 'foobar';
} else if (arr[src] !== undefined) {
alert('This url `' + src + '` already exists');
} else {
alert('This url `' + src + '` is wrong');
}
});
Demo: http://jsfiddle.net/LXgWU/3/
Assuming that your var src_cnt work perfect.
var src_cnt = (editor_val.match(/img/g).length);
if(src_cnt == 1)
{
alert("Plz choose Unique Image");
return false;
}

Categories