Im new to javascript how do i fix this? - javascript

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";
}
}

Related

Why does Javascript give me a uncaught type null error?

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>

Why am I getting this unexpected string error?

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;
}

HTML Javascript dynamic changes to a button

Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:
var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
validUser = true;
document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("results").innnerHTML = "Welcome " + user +"!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
validUser = false;
}
}
function signin() {
if (document.getElementById("btnSignIn").innerHTML == "Sign out") {
validUser = false;
document.getElementById("btnSignIn").innerHTML = "Sign in";
document.getElementById("btnSignIn").style.backgroundColor = "orange";
document.getElementById("results").innerHTML = "Welcome stranger";
document.getElementById("txtUserName").style.visibility = "visible";
document.getElementById("txtPassword").style.visibility = "visible";
setCookie("txtUserName", null, "txtPassword", null, 365); 
}
else {
var user = document.getElementById("txtUserName").value;
var pwd = document.getElementById("txtPassword").value;
if (user.text === "" && user === null &&
pwd.text === "" && pwd === null) {
validUser = false;
}
else if (user === "john#me.com" && pwd === "snow") {
validUser = true;
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("results").innerHTML = "Welcome "+ user + "!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
if (!myCookie) {
validUser = false;
}
}
return false;
}
}
function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toUTCString();
document.cookie = uname + "=" + uvalue + "; " + expires;
document.cookie = pname + "=" + pvalue + "; " + expires;
return true;
}
else {
return false;
}
}
function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var user = getCookie("username");
if (user !== "") {
return user;
}else {
return false;
}
}
else {
return false;
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
<ul class="nav navbar-nav navbar-right">
<li>
<form id="loginform" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" id="txtUserName" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" id="txtPassword" placeholder="Password" class="form-control">
</div>
<button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();" >Sign in</button>
</form>
</li>
</ul>
The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.
You're using outerHTML to set the text of #btnSignIn which replaces the node with just text, since all you provided was text. That removes the #btnSignIn element that you applied the background to. Use innerHTML instead.
You're also missing #results in this demo.
Note, I added return false to an inline onsubmit handler for the form, just for this demo so you can see the state of the button after submitting. You'll probably want to remove that in your actual code.
var validUser;
function init() {
var loginCookie = loginWithCookie();
if (loginCookie === true) {
validUser = true;
document.getElementById("btnSignIn").innerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("results").innnerHTML = "Welcome " + user + "!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
} else {
validUser = false;
}
}
function signin() {
if (document.getElementById("btnSignIn").innerHTML == "Sign out") {
validUser = false;
document.getElementById("btnSignIn").innerHTML = "Sign in";
document.getElementById("btnSignIn").style.backgroundColor = "orange";
document.getElementById("results").innerHTML = "Welcome stranger";
document.getElementById("txtUserName").style.visibility = "visible";
document.getElementById("txtPassword").style.visibility = "visible";
setCookie("txtUserName", null, "txtPassword", null, 365);
} else {
var user = document.getElementById("txtUserName").value;
var pwd = document.getElementById("txtPassword").value;
if (user.text === "" && user === null &&
pwd.text === "" && pwd === null) {
validUser = false;
} else if (user === "john#me.com" && pwd === "snow") {
validUser = true;
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("btnSignIn").innerHTML = "Sign out";
document.getElementById("results").innerHTML = "Welcome " + user + "!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
if (!myCookie) {
validUser = false;
}
}
return false;
}
}
function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = uname + "=" + uvalue + "; " + expires;
document.cookie = pname + "=" + pvalue + "; " + expires;
return true;
} else {
return false;
}
}
function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var user = getCookie("username");
if (user !== "") {
return user;
} else {
return false;
}
} else {
return false;
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
<ul class="nav navbar-nav navbar-right">
<li>
<form id="loginform" class="navbar-form navbar-right" onsubmit="return false;">
<div class="form-group">
<input type="text" id="txtUserName" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" id="txtPassword" placeholder="Password" class="form-control">
</div>
<button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();">Sign in</button>
</form>
<div id="results"></div>
</li>
</ul>
You messed up with replacing the text.
Try to use innerHTML, cause you have text inside the tag.
So inside init() it goes like this:
document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";
Yes, as Michael Coker answer, the problem was replacing the whole html element wit the "sign out" text.
I just wanted to add that that example code must be just for testing dinamicaly dom changes, if you wanna practice login/validation DONT ever do that. I mean, the validation logic.

If else javascript error

I'm attempting to make a simple code so when you insert your name, it inserts it into the text, but if you don't insert your name it asks you to insert your name. The code seems like it should work, but it doesn't. Can anyone help me?
<body>
<h3>Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<p id="dolly"></p>
<button onclick="yourName()">Enter</button>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x == "") {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
</script>
</body>
function yourName() {
var x = document.getElementById("name").value;
if (x.length != 0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
change if (x == "") to if (x != "") and close the function braces.
<body>
<h3>Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<p id="dolly"></p>
<button onclick="yourName()">Enter</button>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x != "") {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
</script>
</body>
Change if(x=="") to if(x!=="" && x.length!==0) and also add a closing brace to close the function.
Full code is given below
<body>
<h3>Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<p id="dolly"></p>
<button onclick="yourName()">Enter</button>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x !== "" && x.length !==0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
</script>
</body>

validate javascript expressions

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"
}
}

Categories

Resources