not getting to my else in jquery javascript - javascript

net mvc application and I am trying to do some validation when someone clicks a button. Here is the code.
function productVerify() {
var intQty = $("#txtQty").val();
var strItemName = $("#item_Name").val();
var strItemDescription = $("#item_Description").val();
var intItemID = $("#item_ID").val();
var intItemPrice = $("#item_Price").val();
var strImgUrl = $("item_ImgUrl").val();
var intQty = $("#txtQty").val();
if (intQty < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
}
else {
//post into cart
alert(strItemName + " " + strItemDescription + " " + intItemID + " " + intItemPrice + " " + strImgUrl + " " + intQty + " " + "I got this far.....! good job")
}
}
this works in jsfiddle but for some reason it does not fully work in my mvc application. it does work on the first if because if I put a 0 in my text box I get the first alert, but nothing happens on the else inside my mvc application. This one part seems so easy, but it is killing me any help would be appreciated.

make sure you using a number in your if statement
//if !num
if (parseInt(intQty) == NaN) {
alert("Please enter a number");
return false;
} else {
//if < 1
if (parseInt(intQty) < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
//if >= 1
} else {
//do something
}
}

Related

If-else statment not working after else is added

I am trying to write a search fnction for an address book which loops through the array of contacts and shows them in a popup. It first worked fine finding and showing the found contacts. After adding the else statement, only "none found" runs. I've tried switching the order and negating the first statement, but that does not work.
$(document).ready(function(){
newSearch.click(function(){
const inputValue = $('#searchcontacts').val();
for(let i = 0; i < contactList.length; i++){
if(inputValue.toUpperCase() === contactList[i].firstName.toUpperCase()){
resultsContent.text(contactList[i].firstName +
" " + contactList[i].lastName +
" " + contactList[i].phoneNumber +
" " + contactList[i].addressText);
} else {
}
};
resultsContent.text('None found')
});
});
You have always set the resultsContent.text('None found') after for loop is executed.
So even if a contact found and that contact is set to the resultsContent, it will be replaced by the resultsContent.text('None found') line
Following code snippet will do the job for you. But I have seen another issue with this code that only the last found contact will be shown in the resultsContent element since you have not accumulated the found results. If you need to show all the contacts you need to accumulate all of them and show
newSearch.click(function(){
const inputValue = $('#searchcontacts').val();
var hasContacts = false;
for(let i = 0; i < contactList.length; i++){
if(inputValue.toUpperCase() === contactList[i].firstName.toUpperCase()){
resultsContent.text(contactList[i].firstName +
" " + contactList[i].lastName +
" " + contactList[i].phoneNumber +
" " + contactList[i].addressText);
hasContacts = true;
} else {
}
};
if( !hasContacts) {
resultsContent.text('None found');
}
});

Vanilla JS addEventListener change on select fires only once

I am using an ecommerce system where I dont have access to HTML code or anything but I can add custom JS code to alter some things and CSS.
I need to edit the shipping info text which is right to Doba dodania text.
My issue is that the event fires only once and not on every select change event.
Can someone help me why it is firing only once? It was needed to add SetTimeOut too.
Please check the page and console logs here:
https://www.privlacuj.sk/Hacik-Offset-Light-Class-AT-21-cena-za-1ks-d2336_1013278452.htm
My code is:
<script type="text/javascript">
function change_doba_dodania() {
var c757_counter = document.querySelectorAll(".c757").length;
var variant = document.querySelectorAll(".c755.variant").length;
var out_of_stock = document.querySelectorAll(".c757.out-of-stock").length;
console.log(c757_counter);
console.log(variant);
console.log(out_of_stock);
if (out_of_stock > 0) {
console.log("Nincs raktaron");
}
if ( ( c757_counter >= 2 ) && ( out_of_stock == 0 ) ){
var dd_text = document.getElementsByClassName("c757")[1].innerHTML;
console.log(dd_text);
var dd_text_array = dd_text.split(" ");
var dd_final = dd_text_array.filter(String);
console.log(dd_final);
if (dd_final[2] == "zajtra") {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " " + dd_final[9] + " " + dd_final[10] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
} else {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " - " + dd_final[9] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
}
}
}
window.addEventListener('DOMContentLoaded', (event) => {
change_doba_dodania();
});
var variant = document.querySelectorAll(".c755.variant").length;
if (variant > 0){
document.querySelector('.c757 select').addEventListener('change', function()
{setTimeout(change_doba_dodania, 1500)});
document.querySelector('.c757 select').addEventListener('change',() =>
setTimeout(console.log, 1000, "Changed")
)
}
If i got your question, your problem is querySelector.
querySelector only selects the first element with the given class name. If you want to select all the elements with the given class name, you should use querySelectorAll.
document.querySelectorAll(".c757 select").forEach(select => {
select.addEventListener(...)
})

Random number generator and if then statements

This code is supposed prompt for two player names and generate a random number between 1 and 6 for each player. It is then supposed to compare those two numbers and provide the output of which player has the higher number or display tie if there is a tie. Sometimes this works and sometimes it does the opposite other times it says both numbers match when they don't.
Anyone have any ideas for me?
var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "
main()
function main()
{
do {
getNames()
rollDice()
displayResults()
endProgram()
}
while (end == "yes")
}
function getNames()
{
playerOne = prompt("Please enter the name of Player One: ")
playerTwo = prompt("Please enter the name of Player Two: ")
}
function rollDice()
{
p1Number = Math.floor((Math.random()*6)+1)
p2Number = Math.floor((Math.random()*6)+1)
if (p1Number > p2Number)
{
return playerOne
}
else if (p1Number < p2Number)
{
return playerTwo
}
else
{
return "Sorry no winner, there was a tie"
}
}
function displayResults()
{
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
window.alert("The winner is! " + rollDice())
}
function endProgram()
{
end = prompt("Do you want to play again? Enter yes or no")
if (end == "no")
window.alert("Thank you for playing");
else if (end == "yes")
return end;
}
window.alert("The winner is! " + rollDice())
This line calls rollDice again for a 2nd time. You display the results of the first call then you re-roll and display the return value of the 2nd call (which may be different).
// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
// recall rollDice
window.alert("The winner is! " + rollDice())
In displayResults(), you are showing the values of p1Number and p2Number before assigning values to them (since that happens within rollDice()).
So your program is working, but your diagnostic output is misleading you.

Submit can't see return false;

I know that I must add return false; to function called in onsubmit (I added it to function and onsubmit="" in HTML). But it doesn't work... Page freshing after pressing Enter or clicking submit button.
JavaScript generated forms:
AnswersHTML += "<div><form onsubmit='cheking(this," + a + "," + b + ", this); return false;'><input class='put' type='text' size='40'><input type='submit' value='Проверить'></form>
and function
function checking(answer, nums, numq, what) {
var usr = answer;
if (isNaN(answer)) {
usr = answer.value;
if (answer.value.length == "") {
usr = "Вы ничего не ввели!"
}
else {
answer = answer.value.toLowerCase();
}
}
if (answer == correct[nums][numq]) {
$(what).parent().parent().append("<br><span class='right'>Ответ: " + usr + "<br>Правильно!</span>").slideDown();
$(what).parent().parent().find(".put").remove();
$("#board").animate({ backgroundColor: '#2ecc71'});
$("#board").animate({ backgroundColor: '#f1c40f'}, 1000);
if (isPhysics[nums][numq]) {
physics++;
$("#presult").text(physics);
}
else {
life++;
$("#lresult").text(life);
}
}
else {
$("#board").animate({ backgroundColor: '#e74c3c'});
$("#board").animate({ backgroundColor: '#f1c40f'}, 1000);
var desciptionToWrong = "<br>" + description[nums][numq];
if (description[nums][numq] == false) {
desciptionToWrong = ""
}
$(what).parent().parent().append("<br><span class='wrong'>Ответ: " + usr + "<br>Неправильно!" + desciptionToWrong + "</span>")
$(what).parent().parent().find(".put").remove();
$(what).remove(".pressenter");
}
return false;
}
Sorry for my possibly disgusting code
Here's the full page https://rawgithub.com/ruslankh/Kurchatovy/master/index.html
Problem in function because when I'm replaced function to just alert, it was fine
Its probably due to type. You have wrong spelling in function call that would cause an error and call goes to server.
Change
'cheking(this," + a + "," + b + ", this);
To
'checking(this," + a + "," + b + ", this);
Your inline onclick has a typo, you left one of the c's out of the function name. This error likely terminates the click handler before it gets as far as the return statement.
Try this,
AnswersHTML += "<div><form data-a='"+a+"' data-b='"+b+"' class='myform'><input class='put... "
SCRIPT
$(function(){
$(document).on('submit','form.myform',function(){
checking(this, $(this).data('a'), $(this).data('b'), this);
return false;
});
});

How to set my HTML Table progressively with Javascript/AJAX and Java Servlet?

Hy everyone! I've got a problem developping a little webapp.
The goal is to search for a specific word in files from a stating folder on the server.
To do that, I've implemented a recursive algorithm using java.io.File and a BufferReader.
When I get the results, I had them in a table using a script in my jsp file :
// Posting founded files in a table.
var files = response.getElementsByTagName("file");
// -> Creating the results table.
var table = "<table width=\"100%\">\n";
for (var i = 0, c = files.length; i < c; i++) {
// -> Building the number of apparence in each file.
var nb = files[i].getAttribute("nb");
var nbSentence = "";
if (nb == 1) { nbSentence = nb + " time in this file."; }
else { nbSentence = nb + " times in this file."; }
// Building and filling the table.
if (i % 2 == 0) { table += "<tr class=\"pair\"><td><a href=" + files[i].firstChild.nodeValue + " target=\"_blank\" >"
+ files[i].getAttribute("name") + "</a></td><td>" + nbSentence + "</td></tr>\n"; }
else { table += "<tr class=\"impair\"><td><a href=" + files[i].firstChild.nodeValue + " target=\"_blank\" >"
+ files[i].getAttribute("name") + "</a></td><td>" + nbSentence + "</td></tr>\n"; }
}
table += "</table>\n";
// -> To end the procedure, we had the table to the right div.
document.getElementById("files").innerHTML = table;
My problem is that with this code, all of the results are printed in one tim in the target table. I would like to see the results comming one by one, everytime a file is found in the algorithm.
I've tried to change the readystate to "3" in the onreadystatestage function :
xhr.onreadystatechange = function() {
if (xhr.readyState >= 3 && (xhr.status == 200 || xhr.status == 0)) {
callback(xhr.responseXML);
document.getElementById("loader").style.display = "none";
document.getElementById("btn").value = "Search";
} else if (xhr.readyState < 3) {
document.getElementById("loader").style.display = "inline";
document.getElementById("btn").value = "Cancel";
}
};
But it doesn't change anything.
Does somebody have an idea? How can I send every founded file one by one ? Do I have t do it in the servlet class ?
The for instruction in the servlet class :
// If the input word name isn't empty, the algorithm is launched.
if (null != wordToSearch && !"".equals(wordToSearch))
{
lstFiles.clear();
searching(new File(contextPath), wordToSearch);
int n = lstFiles.size();
// Priting a message that indicate how many files have been found with the word to search.
emptyFieldMessage = n + " files has been found containing the word '" + wordToSearch + "'!";
output.append("<message>").append(emptyFieldMessage).append("</message>\n");
output.append("<lstFiles>\n");
// Then, files list with :
// - File path in "name" parameter,
// - Number of apparence of the word in "nb" parameter,
// - Formatted path as the value.
for(int i = 0; i < n; i++)
{
output.append("<file name=\"" + lstFiles.get(i) + "\" nb=\"" + lstNbApparence.get(i) + "\" >").append(lstFilesPath.get(i)).append("</file>\n");
}
output.append("</lstFiles>\n");
}
To be more complet, the whole script code :
<script>
// Creating xhr variable.
var xhr = null;
// Creating the "Search" button function.
function request(callback) {
// "Cancel" button case.
if (xhr && xhr.readyState != 0)
{
xhr.abort();
}
// "Search" button case.
else
{
// Calling the good function from external file.
xhr = getXMLHttpRequest();
// Callback and loading icon management.
xhr.onreadystatechange = function() {
if (xhr.readyState >= 3 && (xhr.status == 200 || xhr.status == 0)) {
callback(xhr.responseXML);
document.getElementById("loader").style.display = "none";
document.getElementById("btn").value = "Search";
} else if (xhr.readyState < 3) {
document.getElementById("loader").style.display = "inline";
document.getElementById("btn").value = "Cancel";
}
};
// Calling the Servlet in charge of the recursion algorithm.
var input = encodeURIComponent(document.getElementById("wordName").value);
xhr.open("GET", "/webApp_Search_Merge/ActionServlet?wordName=" + input, true);
xhr.send(null);
}
}
// Creating the reponse function.
function readData(response) {
if (null != response)
{
// Posting the message include in the XML file sending back by the Servlet.
var message = response.getElementsByTagName("message");
document.getElementById("message").innerHTML = message[0].firstChild.nodeValue;
// Posting founded files in a table.
var files = response.getElementsByTagName("file");
// -> Creating the results table.
var table = "<table width=\"100%\">\n";
for (var i = 0, c = files.length; i < c; i++) {
// -> Building the number of apparence in each file.
var nb = files[i].getAttribute("nb");
var nbSentence = "";
if (nb == 1) { nbSentence = nb + " time in this file."; }
else { nbSentence = nb + " times in this file."; }
// Building and filling the table.
if (i % 2 == 0) { table += "<tr class=\"pair\"><td><a href=" + files[i].firstChild.nodeValue + " target=\"_blank\" >"
+ files[i].getAttribute("name") + "</a></td><td>" + nbSentence + "</td></tr>\n"; }
else { table += "<tr class=\"impair\"><td><a href=" + files[i].firstChild.nodeValue + " target=\"_blank\" >"
+ files[i].getAttribute("name") + "</a></td><td>" + nbSentence + "</td></tr>\n"; }
}
table += "</table>\n";
// -> To end the procedure, we had the table to the right div.
document.getElementById("files").innerHTML = table;
}
}
Thanks by advance for your help, Thomas.
I tried to set up a working demo, but with no results. I was also searching why I can't find the way to "sleep" a function and re-execute after 1000 milliseconds or whatever you want. Already found an answer to that, but I think it's not really what did you expected:
A sleep function will kill the browser and possibly the machine.
Javascript is single threaded, so the browser will block while this
executes, and the loop itself will just take up a lot of CPU. I’ve
heard of some libraries that actually do sleep correctly in an
asynchronous manner, but I can’t remember the name right now.
This is a very bad idea. JavaScript is single threaded so while that
for loop is running nothing else can execute (js timers, browser
events, even the UI in most browsers). Try to sleep for 5 or more
seconds and the browser will even warn the user that a script is
running slowly.
Just use setTimeout.
Also speaks about a sleep function into Native Javascript. It seems that it's like a framework or something like that. You can download it and try it at your own. I can't say anything about this because I've never tested, it's just what I found on internet.
I'm sorry to give you bad news.

Categories