Script not executing output - javascript

Im working on switching from python to javascript, not going quite so easily... I think I have nested everything properly, I made sure the inputs were matched to the variables and that the submission was linked to the function, I don not see syntax errors according to my knowledge, but I am just beginning my quest to grapple with javascript. Please help to understand the issues, I do not expect anyone to rewrite the whole thing, I will be doing any research to what ever problems are debugged.
function loanQualify() {
let loan_size = parseInt(document.getElementById('loanBox').value);
let credit_history = parseInt(document.getElementById('creditBox').value);
let income_size = parseInt(document.getElementById('incomeBox').value);
let down_payment_size = parseInt(document.getElementById('paymentBox').value);
let qualify;
if (loan_size >= 5) {
if (credit_history >= 7 && income_size >= 7)
qualify == true;
else if (credit_history >= 7 || income_size >= 7) {
if (down_payment_size >= 5)
qualify == true;
else
qualify == false;
} else
qualify == false;
} else {
if (credit_history < 4)
qualify == false;
else {
if (income_size >= 7 || down_payment_size >= 7)
qualify = true;
else if (income_size >= 4 && down_payment_size >= 4)
qualify == true;
else
qualify == false;
}
}
}
if (qualify == true)
document.getElementById('trueFalse').innerHTML = "You qualify";
else(qualify == false)
document.getElementById('trueFalse').innerHTML = "You don't qualify";
Loan Size: <input type="text" id="loanBox" size="3"><br> Credit History: <input type="text" id="creditBox" size="3"><br> Income Size: <input type="text" id="incomeBox" size="3"><br> Down Payment Size: <input type="text" id="paymentBox" size="3"><br>
<button type="button" onclick="loanQualify()">Qualify?</button>
<div id="trueFalse"></div>

You cannot assign a condition in else and your if() must have == which checks the condition.
if (qualify = true)
document.getElementById('trueFalse').innerHTML = "You qualify";
else (qualify = false)
document.getElementById('trueFalse').innerHTML = "You don't qualify";
Change it to
if (qualify == true)
document.getElementById('trueFalse').innerHTML = "You qualify";
else
document.getElementById('trueFalse').innerHTML = "You don't qualify";

Related

How do I find and use what a function has alerted in Javascript?

I am making a little 'guess the number' game, and I need to find a way to repeat the function based on what it outputs. What I have right now is this:
var input = prompt("Please enter a number between 1 and 100!");
var ranNum = Math.floor(Math.random()*100);
function numCheck()
{
if (input < 1)
alert("Please enter a valid number!");
else if (input > 100)
alert("Please enter a valid number!");
else if (input > ranNum)
alert("Try a little lower!");
else if (input = typeof stringValue)
alert("That is not a number!");
else if (input < ranNum)
alert("Try a little higher!");
else
alert("You got it!");
}
numCheck();
I did this using the inspect option on chrome on the page about:blank. Now that I have the function, I think I need to use another if else statement. It would detect if numCheck() output is You got it!" and if it didn't, it would replay the numCheck function, all the way until the player got the correct number.
How would I do it like that? And if there is a simpler way, what is it?
I made a fiddle that will use alerts and prompt accessible inside the page (I am not sure this what you asked for or not - explain more if not):
HTML:
<div class="numberguess">
<input type="text" id="entry" value="" />
<input type="button" id="send" class="" value="submit" />
</div>
<div id="alert"></div>
JS:
var _alert = document.getElementById('alert');
var ranNum = Math.floor(Math.random()*100);
function numCheck(){
var input = document.getElementById('entry').value;
if (input < 1 && input > 100)
_alert.innerText = "Please enter a valid number!";
else if (input > ranNum)
_alert.innerText = "Try a little lower!";
else if (typeof input != 'string')
_alert.innerText = "That is not a number!";
else if (input < ranNum)
_alert.innerText = "Try a little higher!";
else
_alert.innerText = "You got it!";
}
numCheck();
var el = document.getElementById('send');
el.addEventListener('click', function(){
numCheck();
}, false);
Check this as live exp: Jsfiddle
you can use looping like this code below
var input; // var to hold user input
var ranNum = Math.floor(Math.random()*100);
var win = false; // var if we want to ask another input
var trycount = 0; // don't want to ask for input forever
function numCheck()
{
if (input*1 != input) // check if number first
alert("That is not a number!");
else if (input < 1) // check lower bound
alert("Please enter a valid number!");
else if (input > 100) // check upper bound
alert("Please enter a valid number!");
else if (input > ranNum) // tell a hint
alert("Try a little lower!");
else if (input < ranNum) // tell a hint
alert("Try a little higher!");
else{
alert("You got it!");
win = true; // end the user prompt
}
}
while (!win && trycount < 3){ // while wrong guesses and below 3 tries
input = prompt("Please enter a number between 1 and 100! (" + ranNum + ")");
trycount++; // count the try
numCheck();
}
You need a looping mechanism that will keep prompting the user to input another value.
var ranNum = Math.floor(Math.random()*100);
function numCheck()
{
var input = prompt("Please enter a number between 1 and 100!");
if (input === null)
return false; // user pressed "cancel"
if (input == ranNum) {
alert("You got it!");
return false;
}
if (input < 1)
alert("Please enter a valid number!");
else if (input > 100)
alert("Please enter a valid number!");
else if (input > ranNum)
alert("Try a little lower!");
else if (input < ranNum)
alert("Try a little higher!");
else
alert("That is not a number!");
return true; // continue looping
}
while(numCheck());

Checking for no input in control structure

I am writing this basic control structure for a lesson and I am getting some unexpected behavior.
var answer = prompt('what is your age');
if (answer >= 21) {
alert('good to go!');
}
else if (answer < 21) {
alert('sorry not old enough');
}
else if (answer != typeof Number) {
alert('please enter your age as a number');
}
else if (answer === null) {
alert('you did not answer!');
}
On the very last conditional, I would expect that if I left the prompt empty, it would execute the last alert. However, it just says 'not old enough'. Is it treating no input into the prompt as 0? How can fix this?
Thanks.
Prompt doesn't return null if the user hits OK, to test for emptiness, you need to check if the string is empty answer === ""
You need to move the last two checks to the top since "" < 21 is true:
var answer = prompt('what is your age');
if (answer === '') {
alert('you did not answer!');
} else if (isNaN(answer)) {
alert('please enter your age as a number');
} else if (answer >= 21) {
alert('good to go!');
} else if (answer < 21) {
alert('sorry not old enough');
}

Check if last character is a question mark in javascript

function askQuestion(){
var Prompt = prompt("What yes or no question do you have?", "Type it here...");
var number = Math.floor((Math.random() * 8) + 1);
if(Prompt != null){
if (number == 1){
alert("Signs point yo yes.");
}else if(number == 2){
alert("Yes.");
}else if(number == 3){
alert("Reply hazy, try agian.");
}else if(number == 4){
alert("Doubtful.");
}else if(number == 5){
alert("All signs point to no.");
}else if(number == 6){
alert("Most Likely.");
}else if(number == 7){
alert("Absolutely.");
}else if(number == 8){
alert("It doesn't look good.");
}
}else{
alert("Please re-ask the Magic 8 Ball.")
}
}
<body bgColor="Black">
<center><img src="8ball.png" onClick="askQuestion()" style="cursor:pointer;"></center>
</body>
This is what I have. What I would like to know, is how to see the text typed in the prompt has a question mark at the end.
if Prompt is a string then it should just be as simple as
var lastChar = Prompt.slice(-1);
if(lastChar == '?') { .... }
if (Prompt.slice(-1) === "?") {
...
}
Old answer (substr()):
var lastChar = (Prompt.trim().substr(-1) === '?')
New answer (substring()):
var lastChar = (Prompt.trim().substring(Prompt.length - 1) === '?')
You can use the charAt() method:
var lastChar = Prompt.charAt(Prompt.length-1);
if (lastChar === "?") {
// your logic here
}

Form which redirects by achieved score

I have a html form that has 16 questions that have radio buttons to answer "Yes or No" each having a different value, after q16 the user clicks next and depending on the score the user is taken to the right page ! of 3 pages
Here is the code that I have done was working upto q9 but cannot see where I have gone wrong
function submitForm(){
var totalScore = 0;
if(document.myform.username.value.length == 0){ //make sure a name has been entered
alert('Please enter a name.');
}else if(document.myform.q1[0].checked == false && document.myform.q1[1].checked == false){// make sure q1 has been answered
alert('Please answer question 1.');
}else if(document.myform.q2[0].checked == false && document.myform.q2[1].checked == false){// make sure q2 has been answered
alert('Please answer question 2.');
}else if(document.myform.q3[0].checked == false && document.myform.q3[1].checked == false){// make sure q3 has been answered
alert('Please answer question 3.');
}else if(document.myform.q4[0].checked == false && document.myform.q4[1].checked == false){// make sure q4 has been answered
alert('Please answer question 4.');
}else if(document.myform.q5[0].checked == false && document.myform.q5[1].checked == false){// make sure q5 has been answered
alert('Please answer question 5.');
}else if(document.myform.q6[0].checked == false && document.myform.q6[1].checked == false){// make sure q6 has been answered
alert('Please answer question 6.');
}else if(document.myform.q7[0].checked == false && document.myform.q7[1].checked == false){// make sure q7 has been answered
alert('Please answer question 7.');
}else if(document.myform.q8[0].checked == false && document.myform.q8[1].checked == false){// make sure q8 has been answered
alert('Please answer question 8.');
}else if(document.myform.q9[0].checked == false && document.myform.q9[1].checked == false && document.myform.q9[2].checked == false){// make sure q9 has been answered
alert('Please answer question 9.');
}else if(document.myform.q10[0].checked == false && document.myform.q10[1].checked == false && document.myform.q10[2].checked == false){// make sure q10 has been answered
alert('Please answer question 10.');
}else if(document.myform.q11[0].checked == false && document.myform.q11[1].checked == false){// make sure q11 has been answered
alert('Please answer question 11.');
}else if(document.myform.q12[0].checked == false && document.myform.q12[1].checked == false){// make sure q12 has been answered
alert('Please answer question 12.');
}else if(document.myform.q13[0].checked == false && document.myform.q13[1].checked == false){// make sure q13 has been answered
alert('Please answer question 13.');
}else if(document.myform.q14[0].checked == false && document.myform.q14[1].checked == false){// make sure q14 has been answered
alert('Please answer question 14.');
}else if(document.myform.q15[0].checked == false && document.myform.q15[1].checked == false && document.myform.q15[2].checked == false){// make sure q15 has been answered
alert('Please answer question 15.');
}else if(document.myform.q16[0].checked == false && document.myform.q16[1].checked == false && document.myform.q16[2].checked == false){// make sure q16 has been answered
alert('Please answer question 16.');
}else{ //everything has been entered
var q1Score = 0 //work out the value of q1
if(document.myform.q1[0].checked == true){
q1Score=document.myform.q1[0].value;
}else if(document.myform.q1[1].checked == true){
q1Score=document.myform.q1[1].value;
}
var q2Score = 0 //work out the value of q2
if(document.myform.q2[0].checked == true){
q2Score=document.myform.q2[0].value;
}else if(document.myform.q2[1].checked == true){
q2Score=document.myform.q2[1].value;
}
var q3Score = 0 //work out the value of q3
if(document.myform.q3[0].checked == true){
q3Score=document.myform.q3[0].value;
}else if(document.myform.q3[1].checked == true){
q3Score=document.myform.q3[1].value;
}
var q4Score = 0 //work out the value of q4
if(document.myform.q4[0].checked == true){
q4Score=document.myform.q4[0].value;
}else if(document.myform.q4[1].checked == true){
q4Score=document.myform.q4[1].value;
}
var q5Score = 0 //work out the value of q5
if(document.myform.q5[0].checked == true){
q5Score=document.myform.q5[0].value;
}else if(document.myform.q5[1].checked == true){
q5Score=document.myform.q5[1].value;
}
var q6Score = 0 //work out the value of q6
if(document.myform.q6[0].checked == true){
q6Score=document.myform.q6[0].value;
}else if(document.myform.q6[1].checked == true){
q6Score=document.myform.q6[1].value;
}
var q7Score = 0 //work out the value of q7
if(document.myform.q7[0].checked == true){
q7Score=document.myform.q7[0].value;
}else if(document.myform.q7[1].checked == true){
q7Score=document.myform.q7[1].value;
}
var q8Score = 0 //work out the value of q8
if(document.myform.q8[0].checked == true){
q8Score=document.myform.q8[0].value;
}else if(document.myform.q8[1].checked == true){
q8Score=document.myform.q8[1].value;
}
var q9Score = 0 //work out the value of q9
if(document.myform.q9[0].checked == true){
q9Score=document.myform.q9[0].value;
}else if(document.myform.q9[1].checked == true){
q9Score=document.myform.q9[1].value;
}else if(document.myform.q9[2].checked == true){
q9Score=document.myform.q9[2].value;
}
var q10Score = 0 //work out the value of q10
if(document.myform.q10[0].checked == true){
q10Score=document.myform.q10[0].value;
}else if(document.myform.q10[1].checked == true){
q10Score=document.myform.q10[1].value;
}else if(document.myform.q10[2].checked == true){
q10Score=document.myform.q10[2].value;
}
var q11Score = 0 //work out the value of q11
if(document.myform.q11[0].checked == true){
q11Score=document.myform.q11[0].value;
}else if(document.myform.q11[1].checked == true){
q11Score=document.myform.q11[1].value;
}
var q12Score = 0 //work out the value of q12
if(document.myform.q12[0].checked == true){
q12Score=document.myform.q12[0].value;
}else if(document.myform.q12[1].checked == true){
q12Score=document.myform.q12[1].value;
}
var q13Score = 0 //work out the value of q13
if(document.myform.q13[0].checked == true){
q13Score=document.myform.q13[0].value;
}else if(document.myform.q13[1].checked == true){
q13Score=document.myform.q13[1].value;
}
var q14Score = 0 //work out the value of q14
if(document.myform.q14[0].checked == true){
q14Score=document.myform.q14[0].value;
}else if(document.myform.q14[1].checked == true){
q14Score=document.myform.q14[1].value;
}
var q15Score = 0 //work out the value of q15
if(document.myform.q15[0].checked == true){
q15Score=document.myform.q15[0].value;
}else if(document.myform.q15[1].checked == true){
q15Score=document.myform.q15[1].value;
}else if(document.myform.q15[2].checked == true){
q15Score=document.myform.q15[2].value;
}
var q16Score = 0 //work out the value of q16
if(document.myform.q16[0].checked == true){
q16Score=document.myform.q16[0].value;
}else if(document.myform.q16[1].checked == true){
q16Score=document.myform.q16[1].value;
}else if(document.myform.q16[2].checked == true){
q16Score=document.myform.q16[2].value;
}
//add the scores together
totalScore=parseInt(q1Score)+parseInt(q2Score)+parseInt(q3Score)+parseInt(q4Score)+parseInt(q5Score)+parseInt(q6Score)+parseInt(q7Score)+parseInt(q8Score)+parseInt(q9Score)+parseInt(q10Score)+parseInt(q11Score)+parseInt(q12Scorce)+parseInt(q13Score)+parseInt(q14Score)+parseInt(q15Score)+parseInt(q16Score);
if(totalScore<=15){ //if it's less than or equal to 15 go to this page...
window.location.href='greenzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}else if (totalScore >=16 && totalScore <30){ //go to this page
window.location.href='yellowzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}else {
window.location.href='redzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}
}
}
To avoid this kind of repetitive code, you might want to use loops as Bergi pointed out in his comment. You could do something like this for example: (NOTE - untested!)
function submitForm() {
if(document.myform.username.value.length == 0) { //make sure a name has been entered
alert('Please enter a name.');
return;
}
var totalScore = 0;
var threeAnswerQuestions = [9, 10, 15, 16];
var numberOfQuestions = 16;
for(var i = 1; i <= numberOfQuestions; i++) {
var numerOfAnswers = threeAnswerQuestions.indexOf(i) != -1 ? 3 : 2;
var answerChecked = false;
for(var j = 0; j < numerOfAnswers; j++) {
if(document.myform['q'+i][j].checked) {
answerChecked = true;
totalScore += parseInt(document.myform['q'+i][j].value);
break;
}
}
if(!answerChecked) {
alert('Please answer question ' + i + '.');
return;
}
}
if(totalScore <= 15) { //if it's less than or equal to 15 go to this page...
window.location.href='greenzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
} else if (totalScore >= 16 && totalScore < 30) { //go to this page
window.location.href='yellowzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
} else {
window.location.href='redzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}
}

how to validate dynamic row array values in javascript

pl. advise me how do i validate the array values in javascript.
i am posting the code that i am currently using. the problem is that even after filling up all the values, i still keep getting the validation error message.
pl. advise me where am i wrong
function chkdate() {
var x = document.forms["main"]["date"].value;
if (x == null || x == "") {
document.forms["main"]["date"].focus();
document.forms["main"]["date"].style.background = 'red';
alert("Date Cannot be empty");
return false;
}
}
function chkempty() {
var len = document.forms["main"]["item[]"].length;
if (len == undefined) {
var ic = document.forms["main"]["item[]"].value;
var iq = document.forms["main"]["qty[]"].value;
var ip = document.forms["main"]["price[]"].value;
if (ic == null || ic == "") {
document.forms["main"]["item[]"].focus();
document.forms["main"]["item[]"].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iq == null || iq == "") {
document.forms["main"]["qty[]"].focus();
document.forms["main"]["qty[]"].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ip == null || ip == "") {
document.forms["main"]["price[]"].focus();
document.forms["main"]["price[]"].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
} else for (i = 0; i < len; i++) {
var ica = document.forms["main"]["item[]"][i].value;
var iqa = document.forms["main"]["qty[]"][i].value;
var ipa = document.forms["main"]["price[]"][i].value;
if (ica == null || ica == "") {
document.forms["main"]["item[]"][i].focus();
document.forms["main"]["item[]"][i].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iqa == null || iqa == "") {
document.forms["main"]["qty[]"][i].focus();
document.forms["main"]["qty[]"][i].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ipa == null || ipa == "") {
document.forms["main"]["price[]"][i].focus();
document.forms["main"]["price[]"][i].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
}
}
other details are:-
form name: main
the input boxes item,qty and price are dynamic rows based on user's requirement.
thanks all.
I suggest you as first point to use JQuery in conjunction with validate plugin.
Then for your case follow this example that works fine for me:
$("#testform").validate({
rules: {'qty[]': {required: true,minlength: 1},
//other rules here
},
messages: {
'qty[]': "Select at least one qty",
//other custom error msgs go here
}
});
<input name="qty[]" id="1" value="1" type="checkbox" />
<input name="qty[]" id="2" value="2" type="checkbox" />
<input name="qty[]" id="3" value="3" type="checkbox" />
N.B. that the name of the field of array values must be specified with quotes ('qty[]')
or else you'll get a js error.

Categories