Javascript if statement, adding string into guarantee number checker - javascript

Currently I have this if statement which checks through numbers when registering a guarantee number in a gravity form, however I now need to check through the numbers with a mandatory string that a customer needs to enter immediately before the number as currently they're able to enter just the number and it will search though the guarantee registered numbers whether they have a string in front of them or not...
So for example = searching PO983278 or PT983279 instead of just checking 983278 or 983279.
**Below is a snippet of the current if statement which works great when just checking a number.
**
$productName = $_POST['productName'];
$guaranteeNumber = preg_replace('/[^0-9 ]/','',$_POST['guaranteeNumber']);
if($productName === 'Product One') {
if((300000 <= $guaranteeNumber) && ($guaranteeNumber <= 430000)) {
$confirmation = guaranteeDbCheck($guaranteeNumber);
} else {
$confirmation = 'Invalid Number';
}
} elseif($productName === 'Product TWO') {
if((261000<= $guaranteeNumber) && ($guaranteeNumber <= 411000)) {
$confirmation = guaranteeDbCheck($guaranteeNumber);
} else {
$confirmation = 'Invalid Number';
}
}
echo $confirmation;
**So I'd like to be able to do something like...
**
if($productName === 'Product One') {
if(('PO' + 300000 <= $guaranteeNumber) && ($guaranteeNumber <= 'PO' + 430000))
**But of course this doesn't work, any advice on if anyone has done something similar would be great!
**
Thanks!

$productName = $_POST['productName'];
$guaranteeOriginal = $_POST['guaranteeNumber'];
$guaranteeNumber = preg_replace('/[^0-9 ]/','',$_POST['guaranteeNumber']);
if($productName === 'Product One') {
if((300000 <= $guaranteeNumber) && ($guaranteeNumber <= 430000)) {
$confirmation = guaranteeDbCheck($guaranteeOriginal);
} else {
$confirmation = 'Invalid Number';
}
} elseif($productName === 'Product TWO') {
if((261000<= $guaranteeNumber) && ($guaranteeNumber <= 411000)) {
$confirmation = guaranteeDbCheck($guaranteeOriginal);
} else {
$confirmation = 'Invalid Number';
}
}

Related

Attempting to nest if/else statement in while loop

I'm setting up the following while loop to continue to print a message for each even number entered but print a different message for an odd number and stop:
userEnteredNumber = prompt("Please enter a number:");
while (userEnteredNumber%2 === 0) {
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
}
userEnteredNumber = prompt("Please enter a number:");
console.log(userEnteredNumber);
}
Right now it will continue to print with even number entry and stop if an odd number is entered, but the odd number message won't print. Not really understanding why the odd message won't print. Hoping someone can help clarify it for me!
More like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber == null) { // they clicked cancel
break;
}
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
} else {
document.write(NOT_VALID_MESSAGE + userEnteredNumber);
}
console.log(userEnteredNumber);
}
From your code, you can change it a bit to look like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
break;
}
console.log(userEnteredNumber);
}

What am i doing wrong? it wont run thru every condition

I'm trying to have someone guess a number from 1 to 6. I give them two tries if, by the end of the second try, they don't get it, then else will tell them what the number is but it just won't run. what am I doing wrong?
var number = Math.floor(Math.random() *6) +1;
var answer = false;
var guess = prompt('Take a guess, pick a number from 1 to 6');
if(parseInt(guess) === number) {
answer === true;
} else if (parseInt(guess) > number) {
var guessLess = prompt('To high! Guess less');
if (parseInt(guessLess) === number) {
answer === true;
} else if (parseInt(guess) < number) {
var guessMore = prompt('Guess more');
if(parseInt(guessMore) === number) {
answer = true;
}
}
}
if (answer) {
alert('You got it')
} else {
alert('No. The number was ' + number);
}
}
You are using comparison instead of assignment in the below segment
if (parseInt(guessLess) === number) {
answer === true;
Change it to
if (parseInt(guessLess) === number) {
answer = true;

Trying to make age guessing game in Javascript with counter function; has not worked hitherto

Below is my code thus far for an educational exercise requiring that I make a guessing game with multiple hints and a counter function that terminates after four turns. I've searched SO extensively and found no help. I've reviewed my textbook to no avail. This code is as best as I can do with my present knowledge (class has only been on for a week, so admittedly that is paltry). Any assistance would be greatly appreciated!
if (answerSix != myAge) {
while (guesses <= 4) {
if (answerSix > myAge)
{alert('Too old!')};
guesses++;
else if (answerSix < myAge)
{alert('Too young!')};
guesses++;
}
else if (guesses >= 4) {
{alert('You have guessed too many times! Game over!')};
{break};
}
}
}
else if (answerSix === myAge) {
{alert('Got it like the \'79 SuperSonics!')};
{break}
}
else {alert('Answer is invalid!')}
Give your teacher this answer, and let us know how he will assess you :)
const MAX_GUESSES= 4;
class Game extends React.Component{
state = {started: false, end: false, guesses: 0};
onStart(event) {
event.preventDefault();
if (!this.refs.myAge.value.length)
alert('Give a valid age before starting');
else {
this.setState({started: true, end: false, age: Number(this.refs.myAge.value) });
}
}
onGuess(event) {
event.preventDefault();
const guessed= Number(this.refs.answer.value);
if (this.state.guesses >= MAX_GUESSES ) {
this.setState({end: true, message: 'Failed! you reach max attempts'});
return ;
}
if (!guessed)
alert('Please, put valid answer!')
else {
if(guessed < this.state.age) {
alert('too young!');
this.setState({guesses: this.state.guesses+1})
}
else if(guessed > this.state.age) {
alert('too old!');
this.setState({guesses: this.state.guesses+1})
}
else {
this.setState({
end: true, message: `You win in ${this.state.guesses+1} attempt(s)`
});
return;
}
}
}
renderBeforeStart() {
if (this.state.started || this.state.end) return null;
return (
<div>
<input ref="myAge" type="number" placeholder="give your age before starting" /> years old <br />
<button onClick={this.onStart.bind(this)}>Start Game </button>
</div>
)
}
renderAfterStart() {
if (!this.state.started || this.state.end) return null;
return(
<div>
<input ref="answer" type="number" placeholder="guess the age"/> <br />
<button onClick={this.onGuess.bind(this)}> Guess ></button>
</div>
)
}
renderEnd() {
if (!this.state.end) return ;
return (<p>{this.state.message}</p>)
}
render() {
return (
<div>
{this.renderBeforeStart()}
{this.renderAfterStart()}
{this.renderEnd()}
</div>
)
}
}
ReactDOM.render(<Game />, document.querySelector('section'))
div div input {
font-size:20px;
padding-left:10px;
padding-right:10px;
}
div div button {
font-size : 22px;
margin-top:10px;
margin-left:10px;
cursor: progress;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section />
Thank you all those who provided assistance! I was eventually able to find a solution that I wanted to share for posterity:
var myAge = 29;
var counterSix = 0;
while (counterSix < 4) {
counterSix++;
var answerSix = parseInt(prompt('What\s my age?'));
if (counterSix === 4) {
alert('Let\'s move on');
} else if (answerSix === myAge) {
alert('Got it like the \'79 SuperSonics!');
break;
} else if (answerSix < myAge) {
alert ('Too young!')
} else if (answerSix > myAge) {
alert('Too old!'); questionCounter++
}
}
This is dumbed-down syntax and logic, but I wanted to make it understandable.
//correct age
var age = 6;
//number of times guessed
var counter = 0;
//maximum guesses
var maxCount = 4;
//function that takes a guess as a parameter
function guess(guess){
/*if counter, (number of times guessed),
is equal to or greater than maxCount, (maximum guesses),
alert: 'You have guessed too many times! Game over!'*/
if(counter >= maxCount){
alert('You have guessed too many times! Game over!');
/*else (the number of times guessed is less than maximum guesses))*/
} else {
/*if the type of the parameter 'guess' is not a number,
alert: 'Answer is invalid!'*/
if(typeof guess !== 'number'){
alert('Answer is invalid!');
/*else (the type of parameter 'guess' is a number)*/
} else {
/*if the guess parameter doesn't equal the correct age*/
if(guess !== age){
/*if the guess is less than the correct age,
alert: 'Too young!'*/
if(guess < age){
alert('Too young!');
/*else, (the guess must be greater than the correct age),
alert: 'Too old!'*/
} else {
alert('Too old!');
}
/*else, (the guess parameter must equal the correct age),
alert: 'Got it like the \'79 SuperSonics!'*/
} else {
alert('Got it like the \'79 SuperSonics!');
}
}
/*increment the count of valid guesses by 1*/
counter++;
}
}
guess(4)
//Alerts: 'Too young!'
guess(8)
//Alerts: 'Too old!'
guess(6)
//Alerts: 'Got it like the \'79 SuperSonics!'
guess('hi')
//Alerts: 'Answer is invalid!'
//if guess count > 4
//Alerts: 'You have guessed too many times! Game over!'

javascript throw statement inside jquery ready?

So I am wondering if the following is legal, perhaps its not working due to a syntax error.? Simple validation of four rules on a single search field. Thanks for any help towards an elegant and enlightening solution!
$(function() {
$('input.text').focus(function() {
$(this).removeClass('noSubmitX');
$('.enterX').removeClass('now').text( orig);
}); //reset error status
var orig = "Enter the title you want.";
var msg1 = "Title must be between 3 and 63 characters.";
var msg2 = "Title cannot begin or end with a hypen";
var msg3 = "Title cannot contain a hyphen at character positions 3 and 4";
$('form.xSearch').submit(function() {
var theSearch = $('input.text').val();
var xLong = $('input.text').val().length;
var firstx = (theSearch[0]);
var thirdx = (theSearch[2]);
var fourthx = (theSearch[3]);
var lastx = (theSearch[xLong - 1]);
try {
if (xLong < 2 || xLong > 62) {
throw "msg1";
}
else if (firstx == "-") || (lastx == "-") {
throw "msg2";
}
else if (thirdx == "-") && (fourthx == "-")
{
throw "msg3";
}
}
catch (er) {
if (er == 'msg1') {
$('input.text').addClass('noSubmitX');
$('.enterX').addClass('now').text('Title must be between 3 and 63 characters.');
}
if (er == 'msg2') {
$('input.text').addClass('noSubmitX');
$('.enterX').addClass('now').text('Title cannot begin or end with a hypen');
}
if (er == 'msg3') {
$('input.text').addClass('noSubmitX');
$('.enterX').addClass('now').text('Title cannot contain a hyphen at character positions 3 and 4');
}
}
});
});
I think you're running into trouble with your if statements. They need to be wrapped in parenthesis or wrapped like so:
if (xLong < 2 || xLong > 62) {
throw "msg1";
}
else if (firstx == "-" || lastx == "-") {
throw "msg2";
}
else if (thirdx == "-" && fourthx == "-") {
throw "msg3";
}

Comparing numbers wrong

I have the following JS which compares credit card number length:
validate: function () {
var ccLength = $('.credit-card input[name="cc_number"]').val().length;
var cardType = parseInt($('.credit-card .credit-card-type .selected').attr('rel'));
if (!isNaN(cardType)) {
console.log(ccLength); //11
console.log(provider[cardType].validLength.split(',')); // ["16", "13"]
if (ccLength == 0 || (cardType > 0 && (ccLength < parseInt(provider[cardType].validLength)) || (!$.inArray(ccLength, provider[cardType].validLength.split(','))))) {
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
} else {
if ($('.credit-card input[name="cc_cvv"]').val().length < 3) {
triggerNotification('x', 'You must provide a CCV');
return false;
}
}
} else {
triggerNotification('x', 'Credit card type is not recognized or accepted');
return false;
}
return true;
},
I've included the values of console.log() on the 5th & 6th lines. For some reason, it doesn't fail...
update
provider[cardType].validLength is always either '16,13' or '16'
$.inArray( 16, ['16'] ); //=>-1

Categories

Resources