I'm learning css + js + html rn and while making a simple pop-up message script, i started getting an unexpected string error in the following script:
function myFunction() {
var xbg = prompt("Please enter your name!", "Henry Phillips");
if (person === null || person == "")
{
txt= "Enter your name in the field.";
} else {
txt "Hello" + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
As console says, the string error is specifically located here:
line
There is some errors in your script.
First you forget the = in the else statment.
txt = "Hello " + xbg + "! How are you today?"
----^
The if condition don't test the good variable name, you can replace person by xbg.
if (xbg === null || xbg == "")
// or shorter
if (xbg && xbg.trim())
And finally, you don't call your script another time if user don't enter this name. You can use setTimeout to give some time to the user for read the message before open prompt another time.
setTimeout(myFunction, 500);
See complete fixed code below
function myFunction() {
var xbg = prompt("Please enter your name!", "");
if (xbg === null || xbg == "")
{
txt = "Enter your name in the field.";
setTimeout(myFunction, 500);
} else {
txt= "Hello " + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
myFunction();
<span id="demo"></span>
function myFunction() {
var person = prompt("Please enter your name!", "Put Your Name");
if (person.trim()) {
txt = "Hello, " + person + "! How are you today?"
} else {
txt = "Enter your name in the field.";
}
document.getElementById("demo").innerHTML = txt;
}
myFunction();
<div id="demo"></div>
You can find the edited script here.
so basically you have a typo here: change person with xbg
function myFunction() {
var xbg = prompt("Please enter your name!", "Henry Phillips");
if (xbg === null || xbg == "")
{
txt= "Enter your name in the field.";
} else {
txt ="Hello" + xbg + "! How are you today?"
}
document.getElementById("demo").innerHTML = txt;
}
Related
im currently troubleshooting on why prompt 5 doesnt work, when i delete prompt 5 it does work, im sorry i can't describe my problem with depth just looking for help thanks ! but do feel free to ask questions i didn't specify here
<p id="p"> </p>
<p id="a"> </p>
<p id="b"> </p>
<p id="s"> </p>
<button onclick="prompt1();prompt2();prompt3();prompt4();prompt5();"> prompt </button>
<script>
function prompt1() {
var lname = prompt("Enter your family name", "Potter");
if (lname != null) {
document.getElementById("a").innerHTML =
"Last Name : "+ lname ;
}
}
function prompt2() {
var fname = prompt ("Enter your first name", "Harry");
if (fname != null) {
document.getElementById("b").innerHTML =
"First Name : " + fname ;
}
}
function prompt3() {
var st = prompt ("Enter your section", "Gryffindor");
if (st !=null) {
document.getElementById("s").innerHTML =
"Section : " + st;
}
}
function prompt4() {
var con = confirm ("Do you want to proceed?");}
function prompt5()
if (con != null) { alert( "fname + lname + st ")
else { document.getElementById("p").innerHTML =
"You pressed no";
}
}
</script>
</body>```
Not sure what you want to achieve,but your code is now working with prompt5.
<p id="p"></p>
<p id="a"></p>
<p id="b"></p>
<p id="s"></p>
<button onclick="prompt1();prompt2();prompt3();prompt4();prompt5()">
prompt
</button>
<script>
function prompt1() {
var lname = prompt("Enter your family name", "Potter");
if (lname != null) {
document.getElementById("a").innerHTML = "Last Name : " + lname;
}
}
function prompt2() {
var fname = prompt("Enter your first name", "Harry");
if (fname != null) {
document.getElementById("b").innerHTML = "First Name : " + fname;
}
}
function prompt3() {
var st = prompt("Enter your section", "Gryffindor");
if (st != null) {
document.getElementById("s").innerHTML = "Section : " + st;
}
}
function prompt4() {
var con = confirm("Do you want to proceed?");
}
function prompt5() {
if (con != null) {
alert("fname + lname + st ");
} else {
document.getElementById("p").innerHTML = "You pressed no";
}
}
I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>
I am currently working on some homework for school and I am little stuck with my switch!
I am getting a response up until alert(card) in checkcard();
my problem is, none of the cases will actually validate the type of card that is is in reference too, I am not allowed to use any addons like jQuery etc etc.
I'll post relevant code and be glad to hear from you guys :D I've commented the lines with #### for ease. Also, getcard does return correct card type as wished.
function getCard(){
var cardType = "unknown";
var cardTypeArray = document.getElementById("chooseCard").getElementsByTagName("input");
for(var i = 0; i < cardTypeArray.length; i++){
if (cardTypeArray[i].checked) {
cardType = cardTypeArray[i].value;
}
}
alert ("cardtype is" + cardType);
return cardType;
}
function checkCard(cardNumber){
var errMsg = "";
var card = getCard();
//var cardNumber = document.getElementById("cardNumber").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
alert(card); // works till here #######
switch(card){
case "Visa":
if (parseInt(cardNumber.substring(0,1)!=4) {
errMsg = "card number is not visa \n";
}
break;
case "Mastercard":
if (cardNumber.substring(0,1) !=5) {
errMsg = "card number is not mastercard. \n";
}
break;
case "AmericanExpress":
if (cardNumber.substring(0,2) !=51) {
errMsg = "card number not american express, \n";
}
break;
}
return errMsg;
}
function validator(){
var errMsg = ""; /* stores the error message */
var result = true;
var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;
//document.getElementById("cardName").setAttribute('maxlength',40);
var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum = /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expMonth = document.getElementById("expMonth").value;
var expYear = document.getElementById("expYear").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
if (todayDateMonth > expMonth || todayDateYear > expYear){
errMsg += "expiry date is wrong\n";
result = false;
}
if (!(visaCard || masterCard || americanExpress)){
errMsg += "please select visa, mastercard or american express\n";
result = false;
} /* assumes no errors */
if (cardNumber.length > 16 || cardNumber.length < 15 )
{
errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
result = false;
}else{
checkCard(cardNumber); // Starts here #######
}
if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
errMsg = errMsg + "your card name must only contain alpha characters \n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function init() {
if(document.getElementById("regform")!==null){
var regForm = document.getElementById("regform");// get ref to the HTML element
regForm.onsubmit = validate;
prefill_form();
}
if(document.getElementById("bookform") !=null){
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validator; /* assigns functions to corresponding events */
var cancel = document.getElementById("cancelButton");
cancel.onclick = cancelBooking;
getBooking();
}
}
okay so the problem was that i was not returning an error message or a false result. ill re post the same code as before but what i added to make it work for those interested. thank you for the feed back! i will be taking a few points on board. anyway code is below, look for ###################.
function validator(){
var errMsg = "";
var result = true;
var visaCard = document.getElementById("visa").checked;
var masterCard = document.getElementById("mastercard").checked;
var americanExpress = document.getElementById("americanExpress").checked;
var cardName = document.getElementById("cardName").value;
var regexAlpha = /^[a-zA-Z ]+$/;
var cardNumber = document.getElementById("cardNumber").value;
var regexNum = /^[0-9]+$/;
var date = new Date();
var todayDateMonth = date.getMonth() + 1;
var todayDateYear = date.getFullYear();
var expDate = document.getElementById("expDate").value;
var dateFormat = /^[\d]{2}\/[\d]{4}$/;
if (!dateFormat.test(expDate)){
errMsg += "please select a valid date range\n";
result = false;
}else if (todayDateYear > expDate.substring(3,7)){
errMsg += "please select a valid expiry year\n";
result = false;
} else if (todayDateYear == expDate.substring(3,7) && todayDateMonth > expDate.substring(0,2)){
errMsg += "please select a valid expiry month\n";
result = false;
}
if (!(visaCard || masterCard || americanExpress)){
errMsg += "please select visa, mastercard or american express\n";
result = false;
}
if (cardNumber.length > 16 || cardNumber.length < 15 )
{
errMsg = errMsg + "your card number can only contain 15 to 16 digits \n";
result = false;
}else{
// code below is what i added ######################################
var tempMsg = checkCard(cardNumber);
if (tempMsg != "") {
errMsg = errMsg + tempMsg;
result = false;
};
}
if (cardName.length > 40 || cardName.length < 1 || !regexAlpha.test(cardName))
{
errMsg = errMsg + "your card name must only contain alpha characters \n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function checkCard(cardNumber){
var errMsg = "";
var card = getCard();
var cvv = document.getElementById("CVV").value;
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMaster = /^5[1-5][0-9]{14}$/;
var regAmerica = /^3[47][0-9]{13}$/;
var cvvCheck3 =/^[0-9]{3}$/;
var cvvCheck4 =/^[0-9]{4}$/;
//do with if else
switch(card){
case "Visa":
if (!regVisa.test(cardNumber) || !cvvCheck3.test(cvv)) {
errMsg = "card number is not visa or cvv is wrrong \n";
}
break;
case "Mastercard":
if (!regMaster.test(cardNumber) || !cvvCheck3.test(cvv)) {
errMsg = "card number is not mastercard or cvv is wrong\n";
}
break;
case "AmericanExpress":
if (!regAmerica.test(cardNumber) || !cvvCheck4.test(cvv)) {
errMsg = "card number not american express or cvv is wrong, \n";
}
break;
default:
errMsg = "we cant process this card number \n";
}
return errMsg;
}
The problem is with your code structure I see. You have an if condition inside of switch without any associated else. And without much knowledge of your test conditions I have good reason to believe you are not handling the cases and conditions properly. Simple way to find where your code went wrong is to put debugger; statement in your code. Have your developer tools open, you can do this by pressing F12 in most browsers or just from right click options. It should pause the execution of code there. Then there are two buttons you will see. 1. Play button which will resume code execution at once. 2. Kind of bent arrow, this is important one you can execute code line by line with this one and see which conditions were passed and which part of the code actually executed. Wanted to put this in comment but was too long to fit. If you have problems debugging feel free to comment here.And you can just google developer tools in case you can not open the particular window.
I dont understand what the error means. "Unexpected Identifier". It doesnt really give me any information on the error. I have gotten this error before and I know its probably an error in the code or the way I wrote it. Help please.
<html>
<body>
<script type="text/JavaScript">
// Declare variables
var cardCat; // card category M=morning, A=afternoon, E=evening
var userInput; // user input of cards
var morCard = 0; // morning cards
var aftCard = 0; // afternoon cards
var eveCard = 0; // evening cards
var BR = "</ br>"
var ES = ""
// welcome user, start loop, and ask for card category
document.write("Welcome to Coffee Survey" +BR);
cardCat = prompt("Enter the category of the batch (M, A, or E) or enter Q to quit: " + ES);
userInput = prompt("Enter number of cards in the batch");
// start loop
while (cardCat != "Q") {
if(cardCat == "M")
{ morCard = morCard + userInput; }
else if (cardCat == "A")
{ aftCard = aftCard + userInput; }
else if (cardCat == "E")
{ eveCard = eveCard + userInput; }
};
// Display totals
document.write("Total # of morning cards: " + morCard + BR);
document.write("Total # of afternoon cards: " + aftCard +BR);
document.write("Total # of evening cards: " + eveCard + BR);
//End program
document.write("Thank you for using Coffee Survey");
</script>
</body>
</hmtl>
javascript will be
while (cardCat != "Q") {
document.write("Enter number of cards in the batch");
if(cardCat == "M")
{mornCard = mornCard + userInput; }
else if(cardCat == "A")
{ aftCard = aftCard + userInput; }
else if(cardCat == "E")
{ eveCard = eveCard + userInput }
document.write("Enter category(M, A, or E) or enter Q to quit:);
};
Thing look wrong in your code is placment of End If so correct will be, this is VBSCRIPT not javascript
// start loop
while cardCat != "Q" {
document.write("Enter number of cards in the batch");
If cardCat == "M" Then
mornCard = mornCard + userInput;
Else If cardCat == "A" Then
aftCard = aftCard + userInput;
Else If cardCat == "E" Then
eveCard = eveCard + userInput;
End If'correctly placed end if which is wrong in your code
}
document.write("Enter category(M, A, or E) or enter Q to quit:);
End while
I have done a test for a gender expression -
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(gender || gender1)
{
}
else
{
errorMsg = errorMsg + "please select your gender\n"
}
}
but I would like to be able to write it so that there is no need for an empty positive outcome like this -
if ((alphabetic.test(fname)== false) || (alphabetic.test(lname)== false))
{
alertmsg = alertmsg + "Name should be in alphabets:" + "\n";
}
I am sorry if I appear to be very stupid, I am a complete beginner. any help would be appreciated, thanks
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(!(gender || gender1))
{
errorMsg = errorMsg + "please select your gender\n"
}
}
If I understand correctly:
if(!gender && !gender1) {
errorMsg = errorMsg + "please select your gender\n"
}
Not really sure what you are trying to do but, try using the logical NOT "!":
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if !(gender || gender1)
{
errorMsg = errorMsg + "please select your gender\n"
}
}