Function not running after submitting name into prompt - javascript

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
}
}

Related

how to send 2 parameters from Javascript to controller

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..

Submit button uses both methods at the same time, instead of one, how can I fix this?

I've got an HTML/jQuery Mobile project and I have a dialogue box with a 'create button'. When the 'create button' is pressed I need it to go back to previous page (however it can't access the previous page because the VisualStudio won't let me redirect to a page not in the same folder as my dialogue?) So two questions really, the first is how can I redirect to previous page through this button click. It works like this, you start off on a page and click new profile to create a new profile, once Create is clicked on the dialogue it needs to go back to the main page with new methods, which brings me to the second question.
The button accesses two methods which are checkNewUser(); and toggle(); checkNewUser is basically validation in the form and toggle is to make some DIVs appear and disappear when redirected back to the original page. My main question is how do I get the submit button to do the checkNewUser method first, and if the credentials entered are valid then do the toggle method and redirect to my main page, I hope this makes sense and I don't get down voted into oblivion :-)
<a href="C:\Users\A569417\Documents\AppsMaintenance\UI\Privileges.html" önclick="checkNewUser(); toggle();" data-role="button" data-theme="b"
data-inline="true" data-mini="true" data-icon="check">Create</a>
Here is the checkNewUser method:
function checkNewUser() {
var profileName = document.getElementById("profilename").value;
var companyCode = document.getElementById("companycode").value;
console.log("Attempted login with " + profileName + " and " + companyCode);
if (checkTextboxesValid()) {
}
else {
console.log("failed")
}
and the checkTextboxesValid method that it uses:
function checkTextboxesValid() {
var profileName = document.getElementById("profilename").value;
var companyCode = document.getElementById("companycode").value;
var error_message = "";
// check the fields aren't empty
if (profileName == "") {
error_message = "You must enter a profile name";
} else {
$("#profilename").removeClass("ui-body-f").addClass("ui-body-a");
}
if (companyCode == "" || companyCode == "Company") {
error_message = "You must select a company code";
} else {
}
if (error_message != "") {
$("#message_table").removeClass("hide_element");
$("#login_status_message").html(error_message);
return false;
} else {
return true;
}
then finally this is the Toggled method that hides the divs. I'm not sure how I can get both methods to be used by the submit button and the toggle method only works if the validation is okay. I'm guessing I'd have to combine the two methods or maybe there's a simpler way?
var toggled = false,
div1 = document.getElementById("OldProfile"),
div2 = document.getElementById("NewProfile"),
div3 = document.getElementById("OldProfileButtons"),
div4 = document.getElementById("NewProfileButtons"),
toggle = function () {
if( toggled ) {
div1.style.display = "block";
div2.style.display = "none";
div3.style.display = "block";
div4.style.display = "none";
} else {
div1.style.display = "none";
div2.style.display = "block";
div3.style.display = "none";
div4.style.display = "block";
}
toggled = !toggled;
};
tried using the one answer posted but that one didn't work, the div's weren't affected in that method but I can't see why not, anyone help me out?
Since you have tagged jQUery I would consider changing getElementById to $("#..
However (embed your toggle inside your check):
function checkNewUser() {
var profileName = document.getElementById("profilename").value;
var companyCode = document.getElementById("companycode").value;
console.log("Attempted login with " + profileName + " and " + companyCode);
if (checkTextboxesValid()) {
var toggled = false,
div1 = document.getElementById("OldProfile"),
div2 = document.getElementById("NewProfile"),
div3 = document.getElementById("OldProfileButtons"),
div4 = document.getElementById("NewProfileButtons"),
toggle = function () {
if( toggled ) {
div1.style.display = "block";
div2.style.display = "none";
div3.style.display = "block";
div4.style.display = "none";
} else {
div1.style.display = "none";
div2.style.display = "block";
div3.style.display = "none";
div4.style.display = "block";
}
toggled = !toggled;
};
}
else {
console.log("failed")
}
Glad I could help. I think you should use this refactored code instead:
function checkNewUser() {
var profileName = $("#profilename").value;
var companyCode = $("#companycode").value;
console.log("Attempted login with " + profileName + " and " + companyCode);
if (checkTextboxesValid()) {
var toggled = false,
div1 = $("#OldProfile"),
div2 = $("#NewProfile"),
div3 = $("#OldProfileButtons"),
div4 = $("#NewProfileButtons"),
toggle = function () {
if( toggled ) {
$(div1).css('display','block');
$(div2).css('display','none');
$(div3).css('display','block');
$(div4).css('display','none');
} else {
$(div1).css('display','none');
$(div2).css('display','block');
$(div3).css('display','none');
$(div4).css('display','block');
}
toggled = !toggled;
};
}
else {
console.log("failed")
}

Java script and lightbox close button

i have added a light box function to my web page. everything works. so when i click on an image it goes bigger...
my problem is that there is no close button. how do i get it to close without having to click back.
Here is my code for the light box
window.onload = setupLightbox;
var lightboxOverlay;
var lightboxImage;
function setupLightbox() {
for (i in document.links) {
if(document.links[i].rel == "lightbox"){
document.links[i].onclick = showLightbox;
}
}
}
function showLightbox() {
lightboxOverlay = document.createElement("div");
lightboxImage = document.createElement("img");
lightboxOverlay.style.position = "fixed";
lightboxOverlay.style.top = lightboxOverlay.style.left ="0";
lightboxOverlay.style.width = lightboxOverlay.style.height ="100%";
lightboxOverlay.style.background = "#000";
lightboxOverlay.style.opacity = "0.5";
lightboxOverlay.style.filter = "alpha(opacity = 50)";
document.body.appendChild(lightboxOve…
lightboxImage.onload = showImage;
lightboxOverlay.onclick = closeLightbox;
lightboxImage.src = this.href;
return false;
}
function showImage(){
lightboxImage.style.position = "fixed";
lightboxImage.style.top = lightboxImage.style.left = "50%";
lightboxImage.style.marginLeft = -lightboxImage.width/2 + "px";
lightboxImage.style.marginTop = -lightboxImage.width/2 + "px";
lightboxImage.style.border = "10px solid #fff";
document.body.appendChild(lightboxIma…
}
function closeLightbox(){
lightboxImage.style.opacity = lightboxOverlay.style.opacity = "0";
setTimeout( function() {
lightboxImage.parentNode.removeChild…
lightboxOverlay.parentNode.removeChi…
}, 1);
}
Check the Lightbox should have a css file with it and an image folder too. Specify the css file in the header section so that it can find the image.

close icon doesn't appear

I was trying to add a text popup box on my page, and this code helped me but I need to add a close icon (which is an image in my code)..
but it doesn't work :/
here is my code:
function show_hide_box(an, width, height, borderStyle) {
if (navigator.userAgent.indexOf("MSIE") != -1) {
var browserIsIE = true;
} else { browserIsIE = false; }
var href = an.href;
var boxdiv = document.getElementById(href);
if (boxdiv != null) {
if (boxdiv.style.display=='none') {
move_box(an, boxdiv);
boxdiv.style.display='block';
} else
boxdiv.style.display='none';
return false;
}
boxdiv = document.createElement('div');
boxdiv.setAttribute('id', href);
boxdiv.style.display = 'block';
boxdiv.style.position = 'absolute';
boxdiv.style.width = width + 'px';
boxdiv.style.height = height + 'px';
boxdiv.style.border = borderStyle;
boxdiv.style.backgroundColor = '#FFF';
var inClosebox = document.createElement("div");
inClosebox.setAttribute('id', 'Close');
inClosebox.style.position = 'absolute';
if (browserIsIE) {
inClosebox.style.left = '-1px';
inClosebox.style.top = '0px';
} else {
inClosebox.style.left = '-15px';
inClosebox.style.top = '-15px';
}
inClosebox.style.visibility = 'hidden';
var inImage2 = document.createElement("img");
inImage2.onclick = function () { this.document.close(); };
inImage2.setAttribute('src', '../../Images/closebox.png');
inImage2.setAttribute('width', '30');
inImage2.setAttribute('height', '30');
inImage2.setAttribute('border', '0');
inImage2.style.cursor = 'pointer';
inClosebox.appendChild(inImage2);
var contents = document.createElement('iframe');
contents.scrolling = 'yes';
contents.frameBorder = '0';
contents.style.width = width + 'px';
contents.style.height = height + 'px';
contents.src = href;
boxdiv.appendChild(contents);
boxdiv.appendChild(inClosebox);
document.body.appendChild(boxdiv);
move_box(an, boxdiv);
return false;
}
can any help me please?
That should mean that the path of src is wrong. ie, ../../Images/closebox.png
Add this to your code and see whether this works
inImage2.setAttribute('alt', 'Close');
Even if this doesn't work, it shows you that something else is wrong with the code.
Its a very good practice to add alt attribute to img tag always.
Update:
I just saw this inClosebox.style.visibility = 'hidden';
You are appending img to that and so how are you gonna possibly make it visible when the parent is hidden?
Beats me. Or do you have extra code? If no, please remove that line and try.

Javascript / jQuery form validation

Hey guys. I am currently using a very inefficient script to validate my forms. The code is massive.
The idea with this is if an input box is blank the input label is highlighted red and a div at the top of the form show's information on the error.
function new_receiver(){
if (document.getElementById("RecieversName").value ==""){ //First Name
var txt=document.getElementById("error_receiver");
txt.innerHTML="<p><font color=\"#FF0000\">You need to enter a Name!</font></p>";
window.document.getElementById("RecieversName_label").style.color = '#FF0000';
//Reset
window.document.getElementById("receiver_check_label").style.color = '#000000';
window.document.getElementById("RecieversNumber_label").style.color = '#000000';
window.document.getElementById("RecieversEmail_label").style.color = '#000000';
}else if (document.getElementById("RecieversNumber").value ==""){ //First Name
var txt=document.getElementById("error_receiver");
txt.innerHTML="<p><font color=\"#FF0000\">You need to enter a Phone Number!</font></p>";
window.document.getElementById("RecieversNumber_label").style.color = '#FF0000';
//Reset
window.document.getElementById("receiver_check_label").style.color = '#000000';
window.document.getElementById("RecieversName_label").style.color = '#000000';
window.document.getElementById("RecieversEmail_label").style.color = '#000000'
}else if (document.getElementById("RecieversNumber").value ==""){ //First Name
var txt=document.getElementById("error_receiver");
txt.innerHTML="<p><font color=\"#FF0000\">You need to enter an Email!</font></p>";
window.document.getElementById("RecieversEmail_label").style.color = '#FF0000';
//Reset
window.document.getElementById("receiver_check_label").style.color = '#000000';
window.document.getElementById("RecieversName_label").style.color = '#000000';
window.document.getElementById("RecieversNumber_label").style.color = '#000000';
}else{
from.receiver.submit();
}'
Any ideas or methods to making this process easy as some of my forms have up to 9 input boxes and this validation method is massive!
Cheers Guys!!!
Samuel.
I suggest something like this:
function new_receiver() {
var inputs = [
{
id: "RecieversName",
name: "a Name"
},
{
id: "RecieversNumber",
name: "a Phone Number"
}
// add more here
],
length = inputs.length,
error = document.getElementById("error_receiver"),
hasError = false,
i;
// reset
for (i = 0; i < length; i++) {
document.getElementById(inputs[i].id + "_label").style.color = "#000000";
}
error.innerHTML = "";
for (i = 0; i < length; i++) {
if (document.getElementById(inputs[i].id).value == "") {
error.innerHTML = "<p><font color=\"#FF0000\">You need to enter " + inputs[i].name + "!</font></p>";
document.getElementById(inputs[i].id + "_label").style.color = "#FF0000";
hasError = true;
break;
}
}
if (!hasError) {
from.receiver.submit();
}
}
You can start by trying something like this
$('input').blur(function() {
if($(this).val()==""){
$("#error_receiver").html("<p><font color=\"#FF0000\">This field is required!");
$("label[for=' + this.attr("id") + ']").css('color', '#FF0000');
}
});
Here is a suggestion without jQuery
<form onsubmit="return new_receiver()">
.
.
var formFields = {
"RecieversName": "You need to enter a Name!",
"RecieversNumber":"You need to enter a Number!",
"RecieversEmail":"You need to enter an Email!"
}
function new_receiver(){
var txt=document.getElementById("error_receiver");
//Reset
txt.innerHTML="";
for (var o in formFields) document.getElementById(o+"_label").style.color = '#000000';
for (var o in formFields) {
if (document.getElementById(o).value ==""){
txt.innerHTML="<p><font color=\"#FF0000\">"+formFields[o]+"</font></p>";
window.document.getElementById(o+"_label").style.color = '#FF0000';
return false;
}
}
return true
}
you can use jquery validation plugin http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Categories