I have a very basic code. However I am not able to clear the of the Year with the id (userYOB) on clicking the alert ok. The code works only for the which asks for year. Its not just the clearing of but I also want to bring the place holder back once alert is clicked ok.
Thanks for help.
[fiddle] http://jsfiddle.net/vineetgnair/j8zjjj9r/26/
var d = new Date();
var currentYear = d.getFullYear();
function test() {
var userYearOfBirth = document.getElementById("userYOB").value;
var authorisedAge = 19;
var currentAge = parseInt(currentYear - userYearOfBirth);
//console.log(currentAge);
if (currentAge < authorisedAge) {
alert("You are not authorised to visit the site");
document.getElementById("userYOB").value = " ";
} else {
alert("Welcome to the site!");
userYearOfBirth = " ";
}
}
In else part say
document.getElementById("userYOB").value= " ";
instead of
userYearOfBirth = " ";
Because userYearOfBirth is a simple string so updating it doesn't update the value of textbox.
Please add the following lines after the else part,
document.getElementById("userYOB").value= " ";
document.getElementById("userMOB").value= " ";
document.getElementById("userDOB").value= " ";
This will clear the fields and bring back the placeholder. The reason why
userYearOfBirth = " "
doesn't work is because in the following line the variable actually holds the value not the element itself,
var userYearOfBirth = document.getElementById("userYOB").value;
It would be more advisable if you, replaced the above line with,
var userYearOfBirth = document.getElementById("userYOB");
now you have the reference to the element in the variable. You can easily change the elements value by,
userYearOfBirth.value = " ";
Personally, I prefer the latter method cause its less code. I hope this helps!! :)
Related
I have an object in JS like this:
var getToDoValue = document.getElementById("toDoInput").value;
var nameOfTeamMember = "Tobias";
var person = new Object();
person.task = "Task: " + getToDoValue;
person.member = "Member: " + nameOfTeamMember;
But problem comes when I try to enter the value of "nameOfTeamMember into an if statement:
var mem = person.member;
if (mem == "Tobias") {
console.log("works");
}
This does not work. But when I just console.log "var mem" outside of if statement it gives me "Member: Tobias". Any suggestions? Im still kinda new to JS so prob something with the comparisons
the issue with you code is that the value in person.member is "Member: Tobias" as you pointed out from the result of your console.log, which is the result from the line of code below where you are concatenating the name with the string "Memeber: " and assigning it to the member property.
person.member = "Member: " + nameOfTeamMember;
One option you could use to do the comparison would be:
if (mem.contains("Tobias", 8) {
console.log("works");
}
The 8 is so your search starts after the colon (:) so you don't include "Member:" in it, just what comes after it, which is the actual member name.
I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!
I am developing a chatbot using HTML and javascript. I used an open source ELIZA-style code available online as my starting point. However I noticed an issue with the code:
For example the code says:
var convpatterns = new Array (
new Array (".*my name is (.*)\.", "Nice to meet you $1!"),
new Array ("^I (?:wish |would like )(?:I could |I was able to |to be able to )(.*)\.","What would it be like to be able to $1?"));
uinput = ""
soutput = ""
dialog = ""
function mainroutine() {
uinput = document.mainscreen.BasicTextArea4.value;
dialog = dialog + "User: " + uinput + '\r' + "\n";
conversationpatterns()
dialog = dialog + '\r' + "\n";
updatescreen()
}
function conversationpatterns() {
for (i=0; i < convpatterns.length; i++) {
re = new RegExp (convpatterns[i][0], "i");
if (re.test(uinput)) {
len = convpatterns[i].length - 1;
index = Math.ceil( len * Math.random());
reply = convpatterns[i][index];
soutput = uinput.replace(re, reply);
soutput = initialCap(soutput);
dialog = dialog + "System: " + soutput + '\r' + "\n";
break;
}
}
}
However if I ask the bot "I wish I could fly", the bot will reply "What would it be like to be able to fl"
Noticed the "fly" is missing a "y" letter at the end. It happens everytime no matter what I typed, for example "my name is Michelle", and the bot reply "Nice to meet you Michell", again missing the last letter of the variable.
Remove last dot in your regexp
new Array ("^I (?:wish |would like )(?:I could |I was able to |to be able to )(.*)\.","What would it be like to be able to $1?"))
----------------------------------------------------------------------------------^^
Change to this
new Array ("^I (?:wish |would like )(?:I could |I was able to |to be able to )(.*)","What would it be like to be able to $1?"))
You can test it here:
https://regex101.com/r/hN2gA2/1
My code doesnet add number like 2+2=4 , its adds it like 2+2=22.
I was wondering how I could change this so that it recognizes that my variables are numbers.
var gra=0;
var graTwo=0;
var graThree=0;
var stu = prompt("Who are you grading?");
var gra = prompt("Oh, what is " +stu+ "'s grade?")
if(gra>80) {
alert("Congrats, " +stu+ ". Have a gold star!")
}
else {
alert("Wow, thats awful " +stu+ ", try again")
};
var stuTwo = prompt("Who are you grading?")
var graTwo = prompt(" Oh, what is " +stuTwo+ " 's grade?")
if(graTwo>80) {
alert("Congrats, " +stuTwo+ ". Have a gold star!")
}
else {
alert("Wow, thats awful " +stuTwo+ ", try again")
};
var stuThree = prompt("Who are you grading?");
var graThree = prompt("Oh, what is" +graThree+ "'s grade?")
if(graThree>80) {
alert("Congrats, " +stuThree+ ". Have a gold star!");
}
else {
alert("Wow, thats awful " +stuThree+ ", try again")
};
var add = (gra+graTwo+graThree);
alert(add)
alert("The average grade of your class is ")
You aren't having trouble because of the pluses. You are having trouble because you are assigning graThree to a prompt, which is a string. Use parseInt as the other answer suggests.
Also, you are prompting prompt("Oh, what is" + graThree+ "'s grade?") when you should be using the variable stuThree.
You need to use parseInt or parseFloat.
The prompt function returns string types so your addition concatenates strings instead of adding numbers.
You should always be sure of your variable types before performing any action on them.
Javascript can be a little too nice sometimes.
Using javascript prompt I get two parameters like, search string and search keyword, then search for the keyword and get the number of items found. Then need to show them on the page. Seems to mistake I have made.
<html>
<head>
<script type = "text/javascript">
var counter = 0;
var enter = prompt("Enter your String:");
var search = prompt("Enter words to search:");
var b = search.length;
var a = enter.length - search.length;
for (var y = 0; y <= a; y++)
{
if(b <= enter.length){
if(enter.substring(y,B))
{
counter = counter + 1;
}
b++;
}
else{
document.write("<p>" + "ERROR" + "</p>");
}
document.write("<p>" + "your word:" + enter + "</p>");
document.write("<p>" + "word use:" + counter + "</p>");
</script>
<body>
</body>
</head>
</html>
You are using a variable that is not declared. Remember that Javascript is case sensitive and the variable b is different than B.
You forget to close the for brackets.
You need to compare the substring with the search pattern.
As Sameera Thilakasiri has rightly pointed out, your code is sloppy. If that works for you, great (I suppose), but other people who look at your code may have a hard time following it. Further, sloppy code leads to mistakes that would otherwise be easily caught.
For instance, you have not closed the for loop, which would easily be seen in nicely formatted code.
Beyond the open for loop, the only other problem I see (syntactically) is that JavaScript is a case-sensitive language, which means that b is different from B, which is why your script throws the 'Uncaught ReferenceError: B is not defined' on the line if (enter.substring(y,B)) {.
Try closing your for loop and using a lowercase b on the offending line. Once that is done, you only have to fix the logic errors.
Happy coding.
You can also use indexOf:
var counter = 0;
var enter = prompt("Enter your String:");
var search = prompt("Enter words to search:");
var start = 0;
while(1){
start = enter.indexOf(search,start);
if(start==-1) break;//if nothing found
start++;//next start = current occurrence + 1
counter++;
}
document.write("<p>" + "your word:" + enter + "</p>");
document.write("<p>" + "word use:" + counter + "</p>");