live form results using javascript - javascript

I am trying to provide a message below the fields of a form. The message will depend on what is entered in both fields.
How would I go about making it so it calculates in real time using both the fields and passing it through a calculation?
Here is the fiddle http://jsfiddle.net/6qSeH/
I am using this to get the document values
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
and this at the end to run the function
yearCalculator();

There are many missing pieces in your code.
Firstly you have written code entirely using javascript and trying to use jQuery syntax. So how would you expect it to work.
jQuery to set HTML --- msg.html(value);
javascriptto set HTML --- msg.html = value;
Second When you are checking for Not a Number
It is supposed to look like
val1 === NaN // It is not a string
Also this will never work as NaN is never equal to NaN
Use isNaN() method instead
Third
<div class="message"></div>
supposed to be
<div id="message"></div>
Next you need to assign events to your input. Otherwise it would only work when the page loads for the first time..
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
Otherwise it will only work the first time your script loads.
Cleaned up code
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var msg = document.getElementById('message');
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
function yearCalculator() {
var yearOne = input1.value;
var yearTwo = input2.value;
val1 = parseInt(yearOne);
val2 = parseInt(yearTwo);
if (isNaN(val1) || isNaN(val2)) {
msg.innerHTML = "Please enter a valid year !!";
return;
}
var value1 = yearOne - yearTwo + 18;
if (yearOne == yearTwo) {
msg.innerHTML = "Both years are the same";
}
if (yearOne < yearTwo) {
if (yearTwo < value1) {
msg.innerHTML = "This is a good result";
} else if (yearTwo > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
else {
msg.innerHTML ="Year 1 is greater than Year 2";
}
};
yearCalculator();
Check Fiddle

You can use onchange="yearCalculator()" in both input fileds

First change the class='message' to id='message'. Then try this code:
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var yearOne = input1.value;
var yearTwo = input2.value;
var msg = document.getElementById('message');
function yearCalculator(value1, value2) {
msg.innerHTML='';
val1 = parseInt(value1);
val2 = parseInt(value2);
if (val1 === "NAN" || val2 === "NAN") return;
var value1 = val1 - val2 + 18;
if (val1 == val2) {
msg.innerHTML="Both years are the same";
}
if (val1 < val2) {
if (val2 < value1) {
msg.innerHTML = "This is a good result";
} else if (val2 > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
};
yearCalculator(yearOne,yearTwo);
input1.onkeyup=function() {
yearCalculator(this.value,document.getElementById("input-mini2").value);
};
input2.onkeyup=function() {
yearCalculator(document.getElementById("input-mini").value,this.value);
};

Related

Simple JavaScript function that asks the user for correct answer only 5 times?

I am trying to develop a very simple function with JavaScript that prompts the user to input a number, and then gives them 5 chances to guess the square of the given number.
So for example, if the user puts in 6 in the first prompt, they should put in 36 in the second prompt, but if they fail to make it right, they are getting an error saying that the guessed number is wrong. And they are limited to only 5 chances, so after that, the program does not prompt a user again.
I tried to do something like this to keep things simple:
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries");
if (input2 == input*input) {
alert("Good!");
} else {
prompt("Wrong, enter again!");
}
Am I on a right path here? I mean it is not doing what I want it to do, but I am really stuck at this point. Have no idea how to loop it 5 times, or what to do next.
Try this
function guessSquare() {
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var c = 5;
var message = "Guess its square now in 5 tries";
(function receiveAnswer() {
var input2 = parseInt(window.prompt(message));
if (input2 == input * input) {
alert("Good!");
} else {
c--;
if (c === 0) {
alert("Ran out of attempts!");
} else {
message = "Wrong, enter again! " + c + " attempts left!";
receiveAnswer();
}
}
})();
}
You're missing a closing bracket:
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries")); //<--- here
if (input2 == input*input) {
alert("Good!");
} else {
prompt("Wrong, enter again!");
}
... and you need a loop. The simplest to understand is for:
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));
for (var i = 0; i < 5; i++) {
if (input2 == input*input) {
alert("Good!");
i = 5;
} else {
input2 = prompt("Wrong, enter again!")
}
}
Use do-while
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));
var tries = 1;
do {
if (input2 == input * input) {
alert("Good!");
break;
} else {
prompt("Wrong, enter again!");
}
} while (++tries < 5);
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));
var tries = 0;
do {
if (input2 == input * input) {
alert("Good!");
break;
} else {
input2 = parseInt(window.prompt("Wrong, enter again!"));
}
} while (++tries < 5);

JavaScript credit card validation

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.

How to validate an input as an number in JavaScript

I'm new with JavaScript programming and have been trying to validate a number that is inputted from a user on a php page. Here is the javascript that is included.
var validate_and_create = function(){
var i_number = $("input_number").value;
var isValid = true;
if (i_number === ""){
$("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
isValid = false;
} else {
if (typeof i_number === 'number') {
$("create_n_error").firstChild.nodeValue = "This is a number!";
isValid = true;
} else {
$("create_n_error").firstChild.nodeValue = "This is not a number!";
isValid = false;
}
}
It always prints that the input is not a number even when integer values are inserted in the textbox. So I'm sure its taking the input as a string input. So do I have to convert it to integer so I can validate? or am I doing something wrong?
You can use parseInt to convert the value to integer, like parseInt("55", 10) will return 55.
And something like parseInt("xx",10) returns NaN.
Thanks adeneo, isNaN works for validation.
Code below:
var validate_and_create = function(){
var i_number = $("input_number").value;
var isValid = true;
if (i_number === ""){
$("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
isValid = false;
} else {
if (isNaN(i_number)) {
$("create_n_error").firstChild.nodeValue = "This is not a number!";
isValid = false;
} else {
$("create_n_error").firstChild.nodeValue = "This is a number!";
isValid = true;
}
}

How to Validate Text box on depend of another Text box?

I am Performing Calculation of Student fee Details,There are Two Text boxes,one which is automatically fixed(disabled)as Rs.5000,If i enter value below Rs.5000 value on another Text box then it will calculate subtraction and show balance in result text box.If i enter value above Rs.5000 it should not take that value in second text box.I want to validate text box depending on first text box value.
Here is my body part
my script part
$(".maxmin").each(function () {
var thisJ = $(this);
var max = thisJ.attr("max") * 1;
var min = thisJ.attr("min") * 1;
var intOnly = String(thisJ.attr("intOnly")).toLowerCase() == "true";
var test = function (str) {
return str == "" || /* (!intOnly && str == ".") || */
($.isNumeric(str) && str * 1 <= max && str * 1 >= min &&
(!intOnly || str.indexOf(".") == -1) && str.match(/^0\d/) == null);
// commented out code would allow entries like ".7"
};
thisJ.keydown(function () {
var str = thisJ.val();
if (test(str)) thisJ.data("dwnval", str);
});
thisJ.keyup(function () {
var str = thisJ.val();
if (!test(str)) thisJ.val(thisJ.data("dwnval"));
})
});
You can do on textchanged something like this
$(textbox1).on('change', function () {
if(textbox1.val()==5000){
//do your code
}
else if(textbox1.val()<5000){
//do your code
}
});
Look into the onchange (https://api.jquery.com/change/) or keyup events (https://api.jquery.com/keyup/). Get the values and perform your calculations.

JS can't get my true/false function to display the false output only the true output

I need to write a good that will validate if a number is in between a range of two numbers I can only get the number is valid output no matter what i input in my text box.
function validInputRange(min, max, textbox) {
if (textbox >= min && textbox <= max) {
return true;
} else {
return false;
}
}
function btnValidate_onclick() {
// assign textbox elements to variables for easier access
var numberTextbox = document.getElementById("txtNumber");
var input = parseFloat(numberTextbox.value);
var output = validInputRange(1, 49, numberTextbox.value);
if (output = true) {
var answer = "valid";
numberTextbox.style.backgroundColor = "#00ff00";
} else {
answer = "false";
numberTextbox.style.backgroundColor = "#ff0000";
}
numberTextbox.value = answer;
}
Instead of
if (output = true)
Just do
if (output)
or
if (output == true)
= is used for assignment, while == or === for comparing.

Categories

Resources