window.prompt stop working when adding function - javascript

var user = window.prompt("Welcome to the Vacation Planner. Please enter yourname");
document.getElementById("greeting").innerHTML += ", " + user;
var enterDays = document.getElementById("enterDays");
/*
function.calculateDays(){
var dayMessage = document.getElementById("dayMessage");
if(enterDays <4){
dayMessage.innerHTML = "Short trips are always worth it!";
}
else if(enterDays<7){
dayMessage.innerHTML = "Cool, you'll be there for a week"
}
else{
dayMessage.innerHTML = "You'll have plenty of time to relax and have fun!"
}
}*/
enterDays.onclick = calculateDays;
When I enter this code, the window.prompt work correctly. But when I uncomment the function.calculateDays, the window.prompt stop working. Can anybody explain why is it happening and how to solve it?
Thanks a lot!!!

function.calculateDays is not valid syntax and will throw a syntax error that will prevent future code from calling, to fix it replace it with function calculateDays.

Related

Making a YouTube Webpage and taking user feedback using a if else condition

I want to make a feedback button and I have made the code for the same but it is not working. Below, I have attached parts of my code which are JS codes. I am new here and I am also a little new to HTML so in simple language I want the updated code :)
I have added the whole code below - I don't find any problem with the code.
If I run my code the output is almost correct except when I click on the button and write something in the prompt box and click ok, no text appears!
<button id= "Feedback"onclick="MyFunction()">Feedback Form</button>
<p id = "demo"></p>
<script>
function MyFunction(){
var feedback= prompt("Hi! Put all your comments here, we would love to hear you :)", "good")
var msg;
if(feedback=="good"){
msg="I am happy to hear that! Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="informative"){
msg="That is fantastic, a total video based encyclopedia, Enjoy Watching! ";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="funny"){
msg="Same here! Even I laughed a lot, Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="motivational"){
msg="That is superb, Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="happy"){
msg= "I am so glad you liked it, Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else{
msg="We will surely look into it!";
document.getElementById("demo").innerHTML=msg;
}
}
</script>
THIS QUESTION HAS BEEN ANSWERED!
Hey I used your code and everything is working fine. I don't see any problem. If it is semantically, meaning the behaviour please elaborate on the problem.
<button id= "Feedback"onclick="MyFunction()">Feedback Form</button>
<p id = "demo"></p>
<script>
function MyFunction(){
var feedback= prompt("Hi! Put all your comments here, we would love to hear you :)", "good")
var msg;
if(feedback=="good"){
msg="I am happy to hear that! Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="informative"){
msg="That is fantastic, a total video based encyclopedia, Enjoy Watching! ";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="funny"){
msg="Same here! Even I laughed a lot, Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="motivational"){
msg="That is superb, Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else if(feedback=="happy"){
msg= "I am so glad you liked it, Enjoy Watching!";
document.getElementById("demo").innerHTML=msg;
}
else{
msg="We will surely look into it!";
document.getElementById("demo").innerHTML=msg;
}
}
</script>
Maybe you'll need to load your script after the HTML was loaded. Position the script-tag at the end or use the onload functionality.
The code is good. Maybe in the HTML you are not referencing the JavaScript.
Add <script src="./the/route/to/my/javascript/file/index.js"></script> before the end of the body tag.
You can see that the code is working here:
https://codepen.io/carlos-dubon/pen/VwaRvEp
EDIT:
<button onclick="myFunction()">Feedback Form</button>
<p id="myPElement">
<!-- Output will show here -->
</p>
<script>
function myFunction() {
var feedback = prompt(
"Hi! Put all your comments here, we would love to hear you :)",
"good",
null
);
var msg = "";
var p = document.getElementById("myPElement");
if (feedback == "good") {
msg = "I am happy to hear that! Enjoy Watching!";
p.innerHTML = msg;
} else if (feedback == "informative") {
msg =
"That is fantastic, a total video based encyclopedia, Enjoy Watching! ";
p.innerHTML = msg;
} else if (feedback == "funny") {
msg = "Same here! Even I laughed a lot, Enjoy Watching!";
p.innerHTML = msg;
} else if (feedback == "motivational") {
msg = "That is superb, Enjoy Watching!";
p.innerHTML = msg;
} else if (feedback == "happy") {
msg = "I am so glad you liked it, Enjoy Watching!";
p.innerHTML = msg;
} else {
msg = "We will surely look into it!";
p.innerHTML = msg;
}
}
</script>
Try copy pasting this. It works here.

Uncaught typeError undefined is not a function

I debugged my code plenty, but I am still having issues. This is a class assignment and I asked my professor and he is stunned as well. I am certain that fixing this error will help me with my code, but what I got wrong I am not sure. Could you help? Here is the error
Here my html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic Word - Sample</title>
<script src="magicWord.js"></script>
</head>
<body>
<div>
<h2 align="center">WELCOME TO MAGIC WORD!</h2>
<h3>Please enter your guess on the space below:</h3>
<div>
<input type="text" id="guestGuess" />
<input type="submit" id="submitButton" onclick="javascript:enteredGuess();" />
</div>
</div>
<div>
<h3>Your guesses so far are: </h3>
<div id="userGuesses"></div>
<div>You have guessed: <span id="userAttempts"></span> times</div>
</div>
</body>
</html>
Here is my Javascript
var numOfAttempts = 5;
var numOfGuesses = 0;
var magicWord = "Just";
function guessesUsed(attemptsTaken) {
var numGuessesLeft = document.getElementById("userAttempts");
numGuessesLeft.innerHTML = attemptsTaken;
}
//function guessesLeft(attemptsLeft) {
// var numGuessesUsed = document.getElementById("guessesLeft");
// numGuessesUsed.innerHTML = attemptsLeft;
//}
function listWordsUsed(wordUsed) {
var userTrials = document.getElementbyId("userGuesses").innerText;
var divisor = document.createElement("div");
divisor.innerHTML = "<div id=" + wordUsed + ">" + wordUsed + "</div>";
userTrials.appendChild(divisor);
return;
}
function enteredGuess()
{
//A user will enter a word and the word will be checked against the magic word
//var enterGuess = prompt("What is your guess?", "Enter your guess here");
var theGuess = document.getElementById("guestGuess");
var magicWordResult;
// Used lower case for both instances to compare both words
if (theGuess.value.toLowerCase() == magicWord.toLowerCase())
{
//The user guesses the correct word
magicWordResult = "Your guess was" + theGuess + "! Nice going!";
//document.writeln("Your guess was: " + guestGuess + "\nand the magic word is " + magicWord);
}
else //The user guesses wrong
{
//When user gets it wrong increase by one the numOfGuesses
numOfGuesses ++;
magicWordResult = "Your guess was" + theGuess + ". Nice try, but that's wrong, try again. \nYou have used " + numOfGuesses + " guesses.";
// Subtract the amount of guesses from the amount of attempts
var guessesLeft = numOfAttempts - numOfGuesses;
if (numOfGuesses == numOfAttempts)
{
// When the user has reached all its attemps
magicWordResult = "Sorry, you ran out of guesses. The magic word was " + magicWord + ".";
}
else
{
magicWordResult = "You still have " + guessesLeft + " guesses left.";
}
//To show the number of guesses the user has used
guessesUsed(numOfGuesses);
//To show the number of guesses the user has left
//guessesLeft(guessesLeft);
//Creates a list of the words used by the user
listWordsUsed(theGuess);
}
// Display in an alert mode and show how the user is doing
alert(magicWordResult);
}
Where is my error?
This:
var userTrials = document.getElementbyId("userGuesses").innerText;
gets the text of the "userGuesses" element as a string, but here:
userTrials.appendChild(divisor);
your code treats it as if it were a DOM node. Because there's no "appendChild" property on a String instance, it's undefined, and that explains the error — you're trying to make a function call but the function reference is undefined instead.
edit — oh also that typo in "getElementById()" is also important, as noted by crclayton in a comment. I missed that one :) The general trick to dealing with the
undefined is not a function
error is to try and find a place where your code might come up with undefined instead of a reference to a function. The primary causes, in my experience, are:
Typos, like the "getElementbyId" thing. If the function name is misspelled, JavaScript won't understand that and so it can't give a better error.
Unsatisfied assumptions about what a variable or property refers to, as in the userTrials variable.
Assumption that some function returns a reference to a function, when it in fact (might) return undefined

CRM 2011 - Contact Form Loads with cannot assign to a function result onchange of a birthdate field

Here is the Code that Manipulates the Birthdate and Age, If age is blank I get an error with the field's customized event. I can't seem to figure out why this JavaScript is throwing the "Cannot assign to a function result" error on a Event: onchange, when this error is appearing on form load. Is there a way to Allow the code to have no action if the Birthdate field is blank?
function birthdate_onchange()
{
var age = Xrm.Page.getAttribute("new_age");
var bDay = Xrm.Page.getAttribute("birthdate");
if (bDay.getValue() != null)
{
var now = new Date();
var thisYear = now.getFullYear();
var birthYear = bDay.getValue().getFullYear();
if((bDay.getValue().getMonth()-now.getMonth())>=0)
{
if((bDay.getValue().getMonth()-now.getMonth())==0 && (bDay.getValue().getDate()-now.getDate())<=0)
{
age.setValue(thisYear-birthYear);
}
else
{
age.setValue(thisYear-birthYear-1);
}
}
else
{
age.setValue(thisYear-birthYear);
}
}
else
{
age.getValue()=null;
}
}
I would love some feed back on this as I am new to JavaScript, but want to learn this language very much. Can provide more code or elaboration as needed, as this is just a segment of our Script for Contacts.
Thanks,
PGM
Edit 1 (5/20/2014):
Now that the Age/birthdate field changes are resolved, I am getting a 'fireonchange' object doesn't support property or method 'fireonchange'.
I have a feeling it is coming from this segment of code:
//TODO: could use to be upgraded to 2011 syntax
if (Xrm.Page.getAttribute("srobo_birthdatepre1900").getValue() != null) {
crmForm.all.srobo_birthdatepre1900.style.display = 'inline';
crmForm.all.srobo_birthdatepre1900_c.style.display = 'inline';
crmForm.all.birthdate.style.display = 'none';
crmForm.all.birthdate_c.style.display = 'none';
}
else {
crmForm.all.birthdate.style.display = 'inline';
}
try {
//Sets Age
//TODO: test if this works
Xrm.Page.getAttribute("birthdate").fireOnChange();
}
catch (err1) {
alert("Contact onLoad Error 1" + err1 + " " + err1.description);
}
try {
}
catch (err2) {
alert("Contact onLoad Error 2 " + entity + ": " + err2 + " " + err2.description);
}
} //end on load
I have been trying to switch the CRM 4.0 JavaScript Versioning to the 2011 friendly syntax, but I am still getting the error in my CRM. Could anyone show me where my problem areas are in terms of Syntax?
I have already switched this line:
Xrm.Page.getAttribute("birthdate").fireOnChange();
but still don't see why it would be throwing that fireonchange error?
Thank you so much for all the help so far! I really appreciate it!
Try to change line
age.getValue()=null;
to
age.setValue(null);

Jquery adding items to a list without reloading page

I'm pretty stuck on how this should be achieved, mostly down to my lack of javascript knowledge. This is the code I'm looking at:
http://jsfiddle.net/spadez/VrGau/
What I'm trying to do is have it so a user can type add a "responsibility" in the responsibility field, then click add and have it appear in a list above it. The user can do this for up to 10 responsibilities.
The result would look something like this:
**Responsibility List:**
- Added responsibility 1
- Added responsibilty 2
*responsibility field - add button*
Can anyone explain how this should be done, it seems like it would have to involve ajax. I would really appreciate some more information or even an example.
Thank you.
EDIT: Here is a little bit more clarification. I want this data to be sent to the server as a list of items. I have seen examples of this being implemented, and here is a screenshot:
The user types in something in the text box, then clicks "add" and then it appears in a list above it. This information is what is submitted to the server.
Maybe this one can help also, this limits only 10 list
var eachline='';
$("#send").click(function(){
var lines = $('#Responsibilities').val().split('\n');
var lines2 = $('#Overview').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += '- Added ' + lines[i] + '\n';
}
}
$('#Overview').text(eachline);
$('#Responsibilities').val('');
});
Try it here
http://jsfiddle.net/markipe/ZTuDJ/14/
Something like that maybe?
http://jsfiddle.net/VrGau/10/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#send'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
$responsibilityList.val(newVal+'\n');
$responsibilityInput.val('');
}
}
$inputButton.click(addResponsibility);
Add id for textarea fields
<textarea rows="4" cols="50" placeholder="Responsibilities" id="resplist"></textarea>Add responsibility<br />
<textarea rows="4" cols="50" placeholder="How to apply" id="inputresp"></textarea>
You need Jquery. Use this js code
var i=0;
$("#send").click(addresp);
function addresp()
{
if (i<10)
{
$("#resplist").val($("#resplist").val()+$("#inputresp").val()+'\n');
$("#inputresp").val("");
i++;
}
}
http://jsfiddle.net/br0nsk1y/bDE9W/
It depends on if you want to post data to the server or not. If only in the client side you can do like this.
$("#send").on("click", function(event){
if($("#list li").size() < 10){
$("#list").append("<li>" + $("#responsibilities").val() + "</li>");
}
});
http://jsfiddle.net/VrGau/7/

'Object is not a function' - onclick event

Before I start, no I have no issues that I can find with semicolons, and I'm passing NO values to the function.
When I try to do function "login()" from the console, it works just fine, but when I click an HTML input button to call it, I get "Uncaught TypeError: object is not a function". This is in Chrome by the way.
var aj=new XMLHttpRequest();
var loginf=document.forms["login"];
var regf=document.forms["reg"];
function login(){
var errors=document.getElementById("login_err");
var errs=[];
var uname=loginf['uname'];
var pass=loginf['pass'];
var unameVal=uname.value;
var passVal=pass.value;
if(unameVal.length<4 && unameVal.length>0){
errs.push("Username too short. Try again please.");
}
else if(unameVal.length>18){
errs.push(innerHTML="Username is too long. Try again please.");
}
else if(unameVal.length==0){
errs.push("Please enter a username.");
}
if(passVal.length<8){
errs.push("Password too short. Try again, please.");
}
else if(passVal.length>30){
errs.push("Password is too long. Try again please.");
}
if(errs.length==0){
aj.onreadystatechange=function(){
if(aj.readyState>=4 && aj.status==200){
if(aj.responseText=="suc"){
window.location="/new.php";
}
}
}
aj.open("POST","/inc/php/core.php",false);
aj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
aj.send("login=true&data="+data);
}
else{
errors.innerHTML="<ul>";
for(var x=0;x<errs.length;x++){
errors.innerHTML+="<li>"+errs[x]+"</li>";
}
errors.innerHTML+="</ul>";
}
}
function reg(){
}
And then the input button..
<input type="button" class="submit" value="Log in" style="width:25%" onclick="login();"/>
I see nothing wrong with the code.
Thank you in advance if you can find Waldo in this code.
jsFiddle HERE: http://jsfiddle.net/6sa7M/2
It turns out that the function name "login" was both a reference to the form and function.
I changed "login()" to "loginUser()", and typed "login" into the console, and the form was returned, so they were indeed conflicting with each other.
Thank you again for all the help and special thanks to Marc for the true answer.

Categories