I am trying to make an IF statement in Javascript with the the following code:
<input class="entry" id="modalod" type="text" placeholder="Enter online ID" name="id" required>
<input class="entry" id="pass1" type="password" placeholder="Enter Passcode" name="psw" required>
<input class="entry" id="pass2" type="password" placeholder="Repeat Passcode" name="psw-repeat" required>
<input class="entry" id ="emailtext" type="text" placeholder="Enter Email" name="email" required>
<a href="#" class="loginbtnanchor btn btn-primary btn-md"
onclick="listids()">Login <i class="fa fa-sign-in"></i></a>
var modalok = document.getElementById("modalok");
var idarray = [];
var passcodearray = [];
var emailtextarray = [];
var od = document.getElementById("modalod").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var emailtext = document.getElementById("emailtext").value;
var at = emailtext.indexOf("#");
var period = emailtext.indexOf(".");
modalok.addEventListener("click", function(event) {
if ( ( (at == -1) || (period == -1) ) && ( (od.length < 15) ||
(od.length > 18) ) )
{
alert("NOTE: ONLINE ID MUST BE BETWEEN 15 AND 18 NUMBERS
LONG.\nPASSCODES DON'T MATCH.\nEMAIL INVALID.");
event.preventDefault();
}
else {
idarray.push(od);
passcodearray.push(pass1);
emailtextarray.push(emailtext);
}
});
What's supposed to happen is that ONLY if BOTH the "user" enters an invalid email AND a wrong id then the alert box appears.
However, if just 1 of those conditions happens, the alert box appears.
I am thinking the problem is with my syntax in using the AND/OR in this IF statement.
I tried switching the order of the AND/OR and the conditions, but still couldn't fix it.
Could I please get help on this?
Thanks,
Move these lines inside the click handler:
var od = document.getElementById("modalod").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var emailtext = document.getElementById("emailtext").value;
var at = emailtext.indexOf("#");
var period = emailtext.indexOf(".");
As it stands, you're getting those values immediately (probably on page load). So, for example, od.length is always 0 and at is always -1, etc.
A good way to have debugged this yourself would have been to add a console.log right above the if statement to look at the values you were testing. (E.g. console.log(at, period, od);.) This would have made it clear that those values were incorrect, which would have pointed you in the direction of figuring out where those values were coming from.
I wrote a simple test method, that hopefully helps you.
I took your conditions and testet it with right and wrong values.
Here you go:
function validate(id, num, test){
//if(isIdOrTestInvalid(id, test) && isNumInvalid(num))
if((id <= -1 || test <= -1) && (num < 15 || num > 18))
console.log("Display Error!")
else
console.log("Add data to arrays");
}
//you could split it in separte funtions
function isIdOrTestInvalid(id, test){
return (id <= -1 || test <= -1);
}
function isNumInvalid(){
return (num < 15 || num > 18);
}
validate(1, 16, 2); //all conditions ok -> add data
validate(-1, 16, 2); //only id wrong -> add data
validate(1, 10, 2); // only num wrong -> add data
validate(-1, 10, 2); // id and num wrong -> display error
validate(1, 10, -1); // num and test wrong -> display error
validate(-1, 10, -1); // id, num and test wrong -> display error
Related
In this function, the program does not want to execute my condition if. I stupidly tried to reverse the "if" in "else if", and "else if" to "if" but, of course, that doesn't change anything.
I want when the input value is <12000, the textual content of "amount6" to be changed to "unqualified!
HTML:
<p>CALCUL GAINS PILOTE QUALIFIE</p>
<p class="minimum2">(Points total minimum groupe conseillers + groupe
animateurs = 12000 )</p>
<div class="blocklabel5">
<label for="points amount" class="label6">Entrez points groupe
conseillers</label>
<input type="number" class="amountEnter6" id="amount6">
</div>
<div class="blocklabel6">
<label for="points amount" class="label7">Entrez points groupe
animateurs</label>
<input type="number" class="amountEnter7" id="amount7">
<input type="submit" value="Commissions pilote qualifié" id="submit7"
class="submitEnter7" onclick="calcAmount6()">
</div>
<p id="marginAmount6" class="enterMargin6">0€</p>
</div>
</div>
JAVASCRIPT (calcAmount6)
function calcAmount6(){
var userAmount5 = document.getElementById("amount6").value;
var userAmount6 = document.getElementById("amount7").value;
var oneLevel1 = 12000;
if (userAmount5 + userAmount6 < oneLevel1) {
document.getElementById("marginAmount6").textContent = "Non-qualifié!";}
else if (userAmount5 + userAmount6 >= oneLevel1) {
document.getElementById("marginAmount6").textContent =
Math.round(userAmount5 * 13 / 100) + (userAmount6 * 5 / 100) + "€";}
}
You must convert your strings to numbers
var userAmount5 = Number(document.getElementById("amount6").value);
var userAmount6 = Number(document.getElementById("amount7").value);
Assuming your input is something like
var userAmount5 = document.getElementById("amount6").value; // 10
var userAmount6 = document.getElementById("amount7").value; // 20
then you get this result
userAmount5 + userAmount6 === '1020' // equals true
and not 30 as you may expect.
but if you convert your strings to numbers first you get the desired result
Number(userAmount5) + Number(userAmount6) === 30 // equals true
document.getElementById("id").value would return the value as a string, so you might need to cast it to a number: Number(document.getElementById("id").value)
Try with:
var userAmount5 = parseInt(document.getElementById("amount6").value);
var userAmount6 = parseInt(document.getElementById("amount7").value);
I'm working on a website and wanting to do advanced stuff (at least for me) that is way over my head. My javascript knowledge is extremely limited and need help with this.
I have an html form that accepts 5 text input fields labeled 1-5 representing a percentage distribution. I want to use javascript to do the following:
Read all fields and make sure the total sum is equal to 100.
Disable unnecessary fields when total sum equals 100.
Disable Submit button if total sum is not 100%.
Add the % at the end of the user entry.
I found two separate scripts to accomplish all this, one is javascript and the other one is JQuery. For some reason the JQuery is not working and it is yielding the following error:
Uncaught TypeError: $ is not a function
I've tried modifying the JQuery code, as suggested in multiple solutions online, like the following:
(function($){ "JQuery Code here" })(jQuery);
This get's rid of the error, however the JQuery code does not work.
Both the javascript.js and the JQuery.js files are being propperly enqueued in the WP theme's functions.php file.
Any help will be greately appreciated!!
HTML
<label for="entryFee">Entry Fee:</label>
<input id="entryFee" name="entry_fee" onblur="this.value = '$' + formatNumber(this.value, 1, 2, true)" type="text" value="" placeholder="$100.00" />
<h4>Prize Distribution</h4>
<label for="1stPlace">1st Place:</label> <input id="1stPlace" name="1st_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="60%" maxlength="3" size="4" class="percentageField" required />
<label for="2ndPlace">2nd Place:</label> <input id="2ndPlace" name="2nd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="30%" maxlength="3" size="4" class="percentageField" />
<label for="3rdPlace">3rd Place:</label> <input id="3rdPlace" name="3rd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="10%" maxlength="3" size="4" class="percentageField" />
<label for="4thPlace">4th Place:</label> <input id="4thPlace" name="4th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />
<label for="5thPlace">5th Place:</label> <input id="5thPlace" name="5th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />
<span id="percent">0</span>%
<input id="submitButton" type="submit" value="Submit" disabled>
</form>
Javascript
// Reformats a number by inserting commas and padding out the number of digits
// and decimal places.
//
// Parameters:
// number: The number to format. All non-numeric characters are
// stripped out first.
// digits: The minimum number of digits to the left of the decimal
// point. The extra places are padded with zeros.
// decimalPlaces: The number of places after the decimal point, or zero to
// omit the decimal point.
// withCommas: True to insert commas every 3 places, false to omit them.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
JQuery
(function($){
$('.percentageField').keyup( function () {
//limit the value to between 0 and 100
var thisVal = parseInt($(this).val(), 10);
if (!isNaN(thisVal)) {
thisVal = Math.max(0, Math.min(100, thisVal));
$(this).val(thisVal);
}
//get total of values
var total = 0;
$('.percentageField').each(function() {
var thisVal = parseInt($(this).val(), 10);
if (!isNaN(thisVal))
total += thisVal;
});
//change the value of the current entry to limit sum to 100
if (total > 100) {
$(this).val(thisVal - (total - 100));
total = 100;
}
if (total == 100) {
//enable submit button
$('#submit_button').removeAttr('disabled');
//disable empty input fields
$('.percentageField').each(function() {
var thisVal = parseInt($(this).val(), 10);
if (isNaN(parseInt($(this).val(), 10)) || thisVal == 0)
$(this).attr('disabled','disabled');
});
}
else {
//disable submit button
$('#submitButton').attr('disabled','disabled');
//enable all input fields
$('.percentageField').removeAttr('disabled');
}
//update percentage
$('#percent').html(total);
});
})(jQuery);
The JQuery script was running before the DOM was ready.
Enclosing the entire code set within $('document').ready(function() did the trick:
(function($){
$('document').ready(function()
{ <<JQuery Code>> });
})(jQuery);
Missing link to credit card validation using only JavaScript. Needs to have atleast two different digits and all digits should not be the same. I am unable to return values in the text please help thank you. Here is a link to the exercise.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Credit Card Validation</title>
<meta name="description" content="CHANGE THIS CONTENT DESCRIPTION">
</head>
<body>
<span>Credit Card Number* :</span>
<input class="inputForm" type="number" id="ccn" name="inputStealMoney"
placeholder="Enter Credit Card Number"><span class="restriction" id="CCNSpan"></span>
<button type="button" onclick="CCNSpan">Submit</button>
<br>
<p id="CCNSpan">Text</p>
<script>
function funcCall() {
validFormCCN();
}
function validFormCCN() {
var x, textC;
x = document.getElementById('ccn').value;
//If statement below is blank in the last () paranthesis. It needs to be filled with 'different numbers' to work
if (isNaN(x) && (x%2) ==0 && x.length==16 && ()) {
/*The if statement above is NaN() and x%2==0 is even and x.length is 16 digits and the blank () paranthesis where all the digits cannot be the same with atleast two different digits*/
return true;
}
else {
return false;
}
}
document.getElementById("CCNSpan").innerHTML = textC;
</script>
</body>
</html>
Consider using the following regex pattern:
(\d)(?!\1{15})\d{15}
This asserts that the credit number contains 16 digits, and that the first number does not repeat for the next 15 digits. This implies that there are at least 2 numbers which are not the same.
var str = "1111111111111111";
var patt = new RegExp("(\\d)(?!\\1{15})\\d{15}");
var res = patt.test(str);
console.log(res);
str = "1111111115111111";
res = patt.test(str);
console.log(res);
Of course, in practice, in a production e-commerce site, you would be using much more complex regular expressions. Visa, MasterCard, etc. have rules for how their credit card numbers are formed. You may visit this link for more information.
Your code looks somewhat like an attempt to implement the Luhn algorithm. Implementations for many languages including JavaScript can be easily found.
var luhn10 = function(a,b,c,d,e) {
for(d = +a[b = a.length-1], e=0; b--;)
c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;
return !(d%10)
};
However, not all credit card companies use the Luhn algorithm. This it is recommended to use a library function to validate credit card numbers, e.g. the jQuery Validation Plugin. Another common implementation is provided by Braemoor and a regex-based JS version can be found here.
function validateCcn(value) {
// Accept only spaces, digits and dashes
if ( /[^0-9 \-]+/.test( value ) ) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace( /\D/g, "" );
if ( value.length < 13 || value.length > 19 ) {
return false;
}
for ( n = value.length - 1; n >= 0; n-- ) {
cDigit = value.charAt( n );
nDigit = parseInt( cDigit, 10 );
if ( bEven ) {
if ( ( nDigit *= 2 ) > 9 ) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return ( nCheck % 10 ) === 0;
}
console.log(validateCcn('1234-1234-1234-1234'));
console.log(validateCcn('378282246310005'));
I'm new to javascript and I have input boxes that must not allow a zero value or non-numbers. I originaly tried to create a regular expression but I couldn't seem to get any of them to work correctly. I then came up with the following solution but it seems to only work some of the time. I think my if statements are jacked up. Any help with the code as far as making it better would be greatly appreciated.
HTML:
<input name="payrate" id="payrate"></td>
<input name="hours" id="hours" value="0" onclick="dollars()" onchange="dollars()"></td>
Javascript:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (!isNaN(rate) && !rate == 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
There is no need to check two times for isNaN. Try to simplify the conditions like this:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (rate > 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
You can use <input type="number" min="0.01" step="0.01" value="0.01"> element. See doc. So you will be sure that value rate and hours will be an integer.
As example - you should be able to add whatever you need in this I have commented out some of the additional function calls that were not included - but you should be able to go from here.
<input name="payrate" id="payrate">
<input name="hours" id="hours" value="0" onclick="dollar()" onkeyup="dollar()">
<script>
function dollar(){
var rate = document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!hours || isNaN(hours)){
alert('hours must be a numeric value greater than zeo');
// disableRadio();
// resetForm();
return false;
}
if (!rate || isNaN(rate)) {
alert('rate must be a numeric value greater than zeo');
//disableRadio();
//resetForm();
return false;
}
var adjrate = Math.round(rate*100)/100;
/**
* commented out for example since not included in example code -
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
*/
}
</script>
I want to validate the input field 'putime' in the form because even if the 'putime' input box is empty the result is calculated and nightSurcharges is also added to the cost. So I want to validate 'putime' when it is empty otherwise the script is useless.
function TaxiFare() {
// calculates taxi fare based upon miles travelled
// and the hour of the day in military time (0-23).
var baseFare = 14;
var costPerMile = 7.00;
var nightSurcharge = 20.50; // 9pm to 6am, every night //its flat 20.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert ("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime < 0) || (pickupTime > 23) || (pickupTime==null)) { // note the hours are 0-23. There is no 24 hour, midnight is 0 hours
alert ("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 21 || pickupTime < 6) {
cost += nightSurcharge;
}
document.getElementById("result").innerHTML = "Your taxi fare is: $. " + cost.toFixed(2);
}
And here is the Form from HTML
<form>
Miles for Journey <input type="text" id = "miles" required><br>
Pickup Time <input type = text id = "putime" required><br><br>
<input type="button" value="Calculate Fare" onclick="TaxiFare()">
<input type="reset" value="Clear"><br><br>
<span id = "result"></span>
</form>
I've tried a lot but to no avail....any help is welcomed. Thanks in advance!
how about adding an event handler to the form, in the likes of document.forms[0].submit = validateFunction;
where validateFunction might look like this:
function validateFunction()
{
var allIns = this.getElementsByTagName('input');
if(allIns.namedItem('putime').value == '')
{
alert('silly');
return false;
}
//and other checks go here, too
}