My jsp page contains an array of food with 4 items in it.
When the user enters a food name in the text box which exists in the array I get a output with 4 strings stating whether it is found or not.
Depending on the position of the food item in the array I get the actual answer in the respective string. If the food item entered is the 4th element in array then 4th string written by AJAX gives the correct answer.
My screenshots show the issue
showing the output in case the value entered is Samosa Pav,the second string gives the right output.
showing the output in case the value entered is misalPav,the fourth string gives the right output
What changes so I need to make to ensure that only one and the correct output is received from AJAX call?
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.jsp?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Chuff Bucket</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
%--
Document : index
Created on : 15 Dec, 2016, 7:07:55 PM
Author : KRISHNAJI
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
for(int i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
}
else if (food == "")
{
out.println("Enter a food");
}
else
{
out.println("We don't have " + food);
}
}
%>
</body>
</html>
[1]: https://i.stack.imgur.com/sBHnZ.jpg
[2]: https://i.stack.imgur.com/Xv7fG.jpg
I will just edit the important bits here:
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
int i = 0;
for(i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
break;
}
else if (food == "")
{
out.println("Enter a food");
break;
}
}
if(i >= foodArray.length)
{
out.println("We don't have " + food);
}
Right, in my comment I forgot that all other conditions in your original loop will still print because of the else statement. So I now declared your counter outside of the loop and compared to the length of the array after the loop is exited. That way, if the food they entered is not found, it will only print once at the end. If input is blank, or matches a food, the conditions will be met and it will print the correct response. The counter will cease to increment and will be less than the length of the array, failing the last condition, and leaving you with only the correct response. This should answer your question fully.
Related
I have the following index.html. The objective of the javascript below is to reload the #obj element's data tag, so that it can display multiple images. However, it is possible that one of the images I link the buttons to doesn't exist (in this case, #2).
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
What I expect to happen in the following script is this:
The user presses button1, sees apple
User presses button2, sees nothing
User presses button1, sees apple
However, the third step in that doesn't happen - when I try to reload the object's data after linking to a nonexistent file, it stays blank.
As far as I've been able to gather, this happens in Chrome, and for me works in Safari. I must use the object tag, or some other method that allows for interactive SVG.
One solution you could possibily do is to remove and add the node itself to force a hard reset
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data", "https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
} else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
Try changing the tag to an <img> and setting the "src" attribute.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("src","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("src", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<img id="obj" style='width: 100px'></img>
</body>
</html>
I provide a sample which helps you to solve your problem by making a fake request to that URL.
Chrome does it to inform. Even if you handle onerror correctly with correct error handling with try-catch and every trick with a void or ( ) that is told to prevent error - you can not fix it. It is out of Javascript control.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg");
}
else {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'file/that/doesnt/exist', false);
request.send();
// the object request will be actually modified
if (request.status === 404) {
alert("The file you are trying to reach is not available.");
}
else
{
object.setAttribute("data", "file/that/doesnt/exist");
}
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.
How can I change my code so that if the user presses on cancel the following code will write document.write("#DELETE") or simply leave an empty space?
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var a = prompt("Put a text");
if (a === null || !a) {
document.write("");
} else {
document.write( "Your Text is: " + a );
}
</script>
</body>
</html>
var radiuuss = prompt("Please set the radius");
document.write("Press 1 to put the code or press 2 to clear section");
if (radiuuss === null) {
document.write("#DELETE");
} else {
// document write a message with the value of the radiuuss.
}
I'm trying to create a palindrome checker. And now it seems that my lengthChecker() is no longer being called, nor is the condition whenever a word isn't a palindrome, then say it's not a palindrome. What could be the issue?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lesson #6 Homework</title>
<script type="text/javascript" src="./js/palindrome.js"></script>
</head>
<body>
<h1>Is it a Palindrome?</h1>
<div id="mainCont">
<p>Hello. Please enter a word, and I'll see if it is a palindrome.</p>
<p>Word:
<input type="text" id="str" name="string" />
<button id="checkInput">Submit</button>
</p>
</div>
</body>
</html>
Here is the JS as of now:
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10 ) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert ("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome();
}
function palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
}
if (str == revStr) {
isPalindrome();
} else {
alert(str + " -is not a Palindrome");
}
}
function isPalindrome() {
alert(str + " is a Palindrome.");
}
document.addEventListener("DOMContentLoaded" , function(e){
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
You have your Javascript linked in the head element, so it is executed before the <button id="checkInput"> gets into the DOM. Move it to the end of body or make it deferred.
Because you are tying to access your button, before your page is properly loaded.
You need to get your button and bind your event handler, when DOM is loaded.
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
i found and edited this code from this website for practice but the code wont work with me. the goal of the code is to create a username and password on one page (which for now is limited to premade usernames and passwords) and send that array of information to another page where you can log in using the username and password from the other page. the code looks fine to me but i am an amateur and want to know what is wrong with it. thank you for your answer.
the code for where the username and password are defined is:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
sessionStorage.setItem("unArray", JSON.stringify("bob", "sam"));
sessionStorage.setItem("pwArray", JSON.stringify("lol", "jk"));
</script>
</head>
<body>
</body>
</html>
the code for taking the already created username and password from the above page and using that for a log in page is this:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value;
var pw = document.getElementById("pword").value
var valid = false;
var unArray = JSON.parse(sessionStorage.getItem("unArray"));
var pwArray = JSON.parse(vsessionStorage.getItem("pwArray"));
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" id="Submit" onclick="validate()">
</p>
</form>
</body>
</html>
The following two lines:
sessionStorage.setItem("unArray", JSON.stringify("bob", "sam"));
sessionStorage.setItem("pwArray", JSON.stringify("lol", "jk"));
are not using the JSON.stringify function correctly.
They should be:
sessionStorage.setItem("unArray", JSON.stringify(["bob", "sam"]));
sessionStorage.setItem("pwArray", JSON.stringify(["lol", "jk"]));
See the following link for reference: Mozilla Developer Network.
Per the documentation, the JSON.stringify parameters are defined as the following:
Syntax
JSON.stringify(value[, replacer [, space]])
Parameters
value - The value to convert to a JSON string.
replacer (Optional) - If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.
A detailed description of the replacer function is provided in the JavaScript guide article Using native JSON.
space (Optional) - Causes the resulting string to be pretty-printed.
I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>