Why is the guestName prompt runs again? - javascript

can someone explain this to me? why is it prompt() running again?
And please give me some advice where and what should i change to have a better code. thank you.
function welcomeGuest() {
do {
guestName = prompt("Welcome to my Anime Website! May I know your name?");
if (guestName === null || guestName === false) {
alert("Please come back again.");
window.close();
}
if (guestName === "") {
alert("Please enter your name!");
} else if (guestName.length < 4) {
alert("Your name should be atleast 4 characters!");
} else if (!(isNaN(guestName))) {
alert("Your name can't be number!");
} else {
guestNamesmall = guestName.slice(1, guestName.length);
alert("Welcome to my Anime Website, " + guestName.charAt(0).toUpperCase() + guestNamesmall + "!");
//bodyContent();
}
} while (guestName.length < 4 || !(isNaN(guestName)));
}
// EDIT: adding call to function for demo purposes
welcomeGuest();
EDIT : I'm sorry but my question is when I enter correct input(it should go to else statement, right?) but what happens to me is that the prompt is running again if else statement is met. Why is that?

if you call your welcomeGuest function only once and the condition inside your while loop is respected guestName.length < 4 || !(isNaN(guestName))it will not running again.

The reason prompt is showing up again is because you have it in a loop until your condition is met. Therefore if guestName.length < 4 || !(isNaN(guestName)) is never met, then it will continue to show.
I would avoid using a loop for something like this. You can use css to prevent a user from going through your site instead of continuously prompting them through a loop. Then use events to handle your logic. Do you have a submit/enter button? Then add your logic on the click event. If not, then you can do it on the key down event and look for the enter key.
for example:
var textbox = document.getElementById("idOfTextbox")
with option 1
textbox.addEventListener("keydown", function(event) {
//stop the click event from propagating
event.preventDefault();
//check if enter key was clicked (#13)
if (event.keyCode == 13) {
//do your logic to verify pass/fail of user input
}
});
or option 2
textbox.addEventListener("click", function(event) {
//stop the click event from propagating
event.preventDefault();
//do your logic to verify pass/fail of user input
});
There are other events you may use, but I think these two would be the most beneficial in this situation.

Related

jQuery submit() ignores event handler in nested condition

The problem I am having is that I cannot get the event.preventDefault() to stop the form from submitting in the nested if statements below the first condition testing the Parent Ticket against Original Ticket (which does work as expected). It appears to loose the ability to call the event handler. I have tried return false, event.stopPropagation(), event.stopImmediatePropagation() and nothing works inside the nested conditions. Could anyone shed some light on this for me?
$( "#editTicket" ).submit(function( event ) {
var inputTicket = $('input[name=parentTicketID]').val();
var orginalTicketID = $('input[name=id]').val();
// Parent Ticket cannot be the original ticket
if ( inputTicket == orginalTicketID )
{
$("#parentTicketMessage").html("The parent ticket number is the same the original ticket. Please change the parent ticket number.");
$('input[name=parentTicketID]').focus();
event.preventDefault();
}
if ( inputTicket != orginalTicketID && inputTicket.length > 0)
{
$.get("/resources/cfc/qmdata/ticket.cfc?method=getTicketArray&returnformat=json",{id:inputTicket}).done(function(data)
{
var thisTicketID = JSON.parse(data);
if ( thisTicketID.toString().length == 0 )
{
alert("inside bad ticket");
$("#parentTicketMessage").html("This is not a valid ticket number. Please change the parent ticket number.");
$('input[name=parentTicketID]').focus();
event.preventDefault();
}
else if (thisTicketID[0].ticketID.toString().length > 0 && thisTicketID[0].parentTicketID.toString().length > 0)
{
$.get("/resources/cfc/qmdata/ticket.cfc?method=getTicketArray&returnformat=json",{parentTicketID:inputTicket}).done(function(data2)
{
var thisParentTicketID = JSON.parse(data2);
// We need to check to see if the parentTicketID has not been used on this page.
if (thisParentTicketID.toString().length != 0 && thisParentTicketID[0].ticketID != inputTicket)
{
alert("already used");
// This is the child ticket check and is already being used...stop processing and display message
$("#parentTicketMessage").html("This ticket number is already a child ticket and cannot be used."); $('input[name=parentTicketID]').focus();
event.preventDefault();
}
});
};
});
}
});
'''
What I am trying to accomplish is simply add a message to the form when certain conditions are met and stop the form from being posted until the user fixes the issue.

Trying to get AJAX field to update with returned value (But have to click away before it updates)

Image of form that uses AJAX & JS
I've currently got a maintainer that uses AJAX so when I type a number into the "Order No" field the "Calc" field then gets updated with the "Account" associated with the Order No. It all works however the "Calc" field doesn't fill with the account number until a click away from the Order No field has been done which means that if you were to press the enter key after typing the number the calc is still blank when the checks were made to see if the account and calc numbers are the same.. If you were to type the number then click the "Accept" button the update is then done so the checks then work as expected. So I was wondering if there is a way so that this field could get updated without an extra click.
One solution I came up with was by doing the checks such as account==calc and calc != "" twice so it would run a function where the check would always say that the calc field is blank (as it hasn't updated at this point) which would return an alert saying "Blank" then after returning the alert it would run another function which is exactly the same to do the check again and this time it would work as expected but once the alert is taken out its as if it hasn't got that moments wait which allows for the Calc field to be updated in time.
Its hard for me to post all the code as I use a system that does all the AJAX behind the scenes for you but let me try explain how the AJAX works. Whatever you put in the Order No field will be sent to an external retrieval application that would check to see what account number is associated with the order no and then return it to the Calc field. If then the account and the calc field numbers match submit the form else say its an incorrect order number for that specific customer.
Here are the two JavaScript functions:
function testerRun() {
var abc = ('${row.CUSN760?html}').toString();
var def = document.getElementById("CALCULA001").value;
if (abc == def && abc != "") {
//alert("Order Number & Account Number Match!");
document.getElementById('FORM_M07052').submit();
return true;
} else if (document.getElementById('ORDN760').value == "") {
document.getElementById('FORM_M07052').submit();
return true;
} else {
//alert("Blank First Step!");
finalStep();
}
}
function finalStep() {
if (document.getElementById("CALCULA001").value == "") {
alert("Customers Account Details Need Amending..");
return false;
} else {
var abc = ('${row.CUSN760?html}').toString();
var def = document.getElementById("CALCULA001").value;
if (abc == def && abc != "") {
//alert("Order Number & Account Number Match!");
document.getElementById('FORM_M07052').submit();
return true;
} else if (document.getElementById('ORDN760').value == "") {
document.getElementById('FORM_M07052').submit();
return true;
} else {
alert("Order Number & Account Number Do Not Match!");
return false;
}
}
}​
And here is where the script is called:
<input class="btn btn-primary accept" id="btnaccept" name="btn_accept" onclick="testerRun();return false" type="submit" value="Accept" />
#Shreyas Sorry there is no blur or change as im using a system called MRC and so they use behind the scenes AJAX scripts to handle thigns like this what I don't have access too so I need some sort of work around. Its only an issue when the user clicks enter in the order no field after entering the order number without doing anything else on the form as it doesn't update until the order number is deselected.
document.getElementById('ORDN760').onkeydown = function(event){
if (event.which == 13 || event.keyCode == 13) {
document.getElementById('ORDN760').blur();
testerRun();
}
}
Function call not working though doesn't seem to do anything just sits there after blur.
Add a keypress handler on the Order No field, which listens for the Enter key, and submits the form when Enter is pressed.
document.getElementById('ORDN760').onkeydown = function(event){
if (event.which == 13 || event.keyCode == 13) {
document.getElementById('ORDN760').blur();
return false;
}
}

Get an INPUT value from HTML Input

I am trying to make this Guessing Game. Below is the repo on Github.
https://github.com/christsapphire/Guessing-Game
I wrote the logic in guessing-game.js and it worked fine. Which I am using userGuess = prompt("Guess a number"). However, if I click cancel on this prompt, it will keep asking (maybe thats why??).
I tried to translate this to jQuery, using userGuess = $('#input').val(); and it encountered a bug. The webpage crashed after I click the "Submit" button.
I want when a user click "Submit" button on the webpage, it runs this function below.
function checkUserInput() {
for (var valid = false; !valid;) {
//I suspect these two below
// userGuess = parseInt($('#submit').val(), 10)
//userGuess = parseInt(prompt("Guess a number"), 10);
//-----------
if ((userGuess >= 1) && (userGuess <= 100)) {
if (repeatAnswer(userGuess, userGuessHistory)) {
$('#status').text("You chose that number before! Choose another number!");
} else {
valid = true;
userGuessHistory.push(userGuess);
return true;
}
} else {
$('#status').text("That number is invalid! Please enter a number between 1-100");
}
}
}
I think when I enable userGuess = $('#submit').val() it is repeatedly trying to take an input value from the Input html element, so it crashed.
Please help! Thanks before
It looks like you are really wanting to get the value of the input, not the submit button:
$("#input").val();
Are you trying to attach your function to the submit button? That would be:
$("#submit").click(function(){
CheckUserInput();
});

ALERT Box not showing up, issue within code, not browser

I've currently created this code to check for an array (For the Login) before moving to the next array to corroborate the password. For some reason, there's a specific instance within the code preventing a javascript prompt or alert box from popping up. I've done trial and error and it appears to be an issue with the while statement overall. But, further testing is not revealing anything obvious.
while(loginSelection != true)
{
alert("Welcome to the Ballot Design Process");
var loginUsername = prompt("Please enter in your username: ");
for(checkFor; checkFor <= userID.length; checkFor++)
{
if(loginID == userID(count))
{
if(user_password == password(checkFor)
{
loginPassword = prompt("Please enter in your password: ");
}
}
else
{
arrayPos += 1;
if(arrayPos == userID.length-1)
alert("Sorry, you did not enter a correct identification.");
}
}
}
You are missing a closing bracket on your if statement:
if(user_password == password(checkFor)) <<<<<
I recommend checking your javascript code with something like http://www.jshint.com if your debugger/IDE isnt picking it up.

How to check all text boxes are empty before clicking calculate

Hi all im new to jscipt,,, well, programming in general to be honest, but learning slowly for personal use.
I seek guidence on how i could place all the textboxes(inputs) in my index file into a list container, loop through them to check if they are empty or not before clicking the calculate button. If they are empty then inform the user of which one is empty.
Also, is there a way of preventing users from entering text into the textboxes and numbers only.
Background: im creating a form that requires all fields to be populate with numbers(in hours), a graph will then be generated from those values.
ive placed the file in skydrive for folks to download with the link below.
Index file
I did try the following but this alerts me regardless of weather the texboxes are populate or not.
function checkInputsGenerateGraph()
{
if( $('#hutz-hoursInput').val() == ""||$('#hutz-weeksPerYearInput').val() == ""||$('#hutz-jobsPerWeekInput').val() == ""||$('#hutz-hourlyMachineRateInput').val() == ""||$('#hutz-maintneneceDowntimeInput').val() == ""||$('#hutz-scrapRateInput').val() == ""||$('#hutz-toolsPerJobInput').val() == ""||$('#hutz-timeToLoadToolInput').val() == ""||$('#hutz-timeToSetPartsInput').val() == "")
{
alert('One them is empty!!');
}
else
{
$("#hutz-graph").slideDown();
$("#hutz-lblImproveMyProcess").slideUp();
$("#hutz-hoursInput").slideUp();
$("#hutz-weeksPerYearInput").slideUp();
$("#hutz-jobsPerWeekInput").slideUp();
$("#hutz-ourlyMachineRateInput").slideUp();
$("#hutz-ntneneceDowntimeInput").slideUp();
$("#hutz-scrapRateInput").slideUp();
$("#hutz-toolsPerJobInput").slideUp();
$("#hutz-timeToLoadToolInput").slideUp();
$("#hutz-timeToSetPartsInput").slideUp();
$("#hutz-lblMachineDetails").slideUp();
$("#hutz-lblPartSetting").slideUp();
$("#hutzcurrencyPreferenceInput").slideUp();
createChart();
}
}
First off, give all the required elements a common class, for examples sake we'll call this required:
<input type="text" class="required" id="hutz-hoursInput" />
Then, when your checkInputsGenerateGraph() function is called, you can loop over the required elements and check them:
$('.required').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
}
});
You could also do something like the following to remove all non-digits from your inputs:
$('.required').change(function() {
this.value = this.value.replace(/[^\d]+/, '');
});
See it in action
Hope that points you in the right direction!
edit
Here's a complete example:-
function checkInputsGenerateGraph() {
var isValid = true;
$('.example').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
isValid = false;
}
});
if (isValid) {
alert('do calculations!');
}
}
So, loop over all of the elements first, and make sure they are all populated. If not, set isValid to false so that once the loop completes, the calculations are not performed.

Categories