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();
});
Related
I have an HTML input on my page. The user is able to type text into it. When he types in a command, that I specified, and presses enter, the page outputs information into the input.value. If the user types in something random and confirms his input, the page just outputs: "Unknown command.", again into to input.value.
I made a striped down Fiddle here: JSFiddle
The Problem:
When I type in: test and press enter, the value changes to: This is kind of working…. I know want to type in something new, but I first have to highlight, or delete the This is kind of working… text, which is really not intuitive.
Is there a way to change my script, so that when I'm in the input and I press any button, that is not button Nr.13 aka "Enter", the page just makes the value of the input, the button, that has been pressed? So that the user can just start typing in something new, after receiveing a value and doesn't have to delete the value that I put in there.
I tried adding an additional .onkeypress function, but it destroyed everything, so I didn't do it the right way.
This is my current JS:
var clInput = 0;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
HTML:
<input id="inputMain" name="inputMain" autofocus>
I have updated your code a bit to do exactly what you want. What was essentially done was to:
Keep track of when you pressed 13 - Enter.
Then if 13 - Enter was previously pressed, just make sure to clear the input.
You can check the demo here: https://jsfiddle.net/nh6c7ugf/
var clInput = 0; // Note: Ignore Upper- / Lower-Case in input?
var isEntered = false;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
// clear the value
if (isEntered) {
isEntered = false;
document.querySelector("#inputMain").value = '';
}
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
isEntered = true;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
Sorry if I don't understand what you are trying to say
but if you want that the user can just start typing in something new, after receiving value and doesn't have to delete the value that you put in there.
you can do
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
document.querySelector("#inputMain").selct();
}
This will select all the text of the input field and when the user will type something the previous value of the field will be deleted
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.
In Chrome (55.x) if a user attempts to enter mismatched type into an input (in my case a number input) nothing outwardly appears to happen. To enhance usability I'd like to display a popup to let users know they're trying to enter invalid data rather than have them thinking the input is 'broken'.
This is easily achieved with pure JS in FF (which allows mismatched type to be entered, it just isn't valid):
input.addEventListener('input', function() {
if (!this.checkValidity()) {
this.value = '';
console.log('please enter a number!');
}
}
Because Chrome doesn't actually input anything, however, the validity check always passes as the input is empty; it doesn't appear to do anything with the incorrect input except ignore it.
Is there any way to override this behaviour, or otherwise achieve the intended effect?
Sure, you could do a listener for keyup and it will give you the key that was pressed.
<script>
var numInput = document.getElementById("num");
numInput.addEventListener("keyup", function(e) {
if (isNaN(String.fromCharCode(e.which))) {
alert("Must be a number");
}
});
</script>
How about setting a last input value and check like this?
let input = document.querySelector('input');
let lastInput = input.value;
input.addEventListener('input', (e) => {
if (e.target.value === lastInput) {
alert("Input must be a number");
}
lastInput = e.target.value;
});
I have a simple function that checks a field is a number, and that it begins "000".
This is checked using "onblur", to provide instant(ish) feedback to the user.
My code:
function IsNumeric(input)
{
return (input - 0) == input && (''+input).trim().length > 0;
}
function checkNumber(field) {
if (!IsNumeric(field.value)) {
seterrorlabel("That's not a number");
toggleButton('SubmitButton', true);
} else if (!(field.value.substring(0, 3) == "000")) {
seterrorlabel("All numbers must begin 000. One 0 for external. Two 0's for an international number.");
toggleButton('SubmitButton', true);
} else {
toggleButton('SubmitButton', false);
seterrorlabel("");
}
}
function toggleButton(button,disableit) {
var input = document.getElementById(button);
input.disabled = disableit;
}
function seterrorlabel(message) {
var thelabel = document.getElementById('numbererror');
thelabel.innerHTML = message;
}
The problem is that in Internet Explorer 11, the onblur function appears to work only once. I can enter a number such as "001234" and receive the expected error, but after correcting the error, and entering a valid "0001234" the label is not cleared.
Similarly, if i add letters, to make this non-numeric, the label does not update.
In Chrome, this works pefectly however, and it updates each time i would expect onblue to fire.
Any ideas?
just want to confirm that when you enter '001234' and hit the button, does your button gets enabled when focus again to the textbox
This was fixed in Internet Explorer by using a different function for IsNumeric - the previous one was causing issues, though they were not showing the console until changing the function definition to global scope.
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;
}
}