Why is the logical 'OR' not working on my second 'IF' condition? - function

I'm learning about 'if..else' and logical operators. I've written some code to help me learn as a go, here's the whole thing;
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Function scope example</title>
</head>
<body>
<button>Press me</button>
<script>
const button = document.querySelector("button");
function greet() {
let name = prompt("What is your name?");
alert(`Hello ${name}, nice to see you!`);
let age = prompt(`${name}, how old are you?`);
let favoriteFood = prompt(`${name}, what\'s your favorite food?`)
if (favoriteFood == 'Fish fingers' || favoriteFood == 'fish fingers'){
if (age > 16){
alert(`You\'re ${age} and you eat ${favoriteFood}??`)
alert("That's lame " + name + ", grow up.")
} else if(age<16){
alert('Yummy kiddo!')
}
}if(favoriteFood == 'Ham' || favoriteFood == 'ham'){
alert('That\'s Ponyos favorite food too!')
}else if(favoriteFood == 'Cheese' || favoriteFood == 'cheese'){
alert('Cheese is good for the soul')
}else {
alert(`Cool, ${name}, that sounds yum!`)
}
button.addEventListener("click", greet);
</script>
</body>
</html>
Here's the part that's not working as expected;
if (favoriteFood == 'Fish fingers' || favoriteFood == 'fish fingers'){
if (age > 16){
alert(`You\'re ${age} and you eat ${favoriteFood}??`)
alert("That's lame " + name + ", grow up.")
} else if(age<16){
alert('Yummy kiddo!')
}
The first condition "Fish fingers" works when entered into the prompt and runs the following code depending on "age" but the second condition "fish fingers" does not. It skips to the "else" at the end.
I expected that when either 'Fish fingers' or 'fish fingers' were entered into the prompt, the following code would run but it doesn't.
Ive tried some reading it all again and playing with a sandbox which returned the result iIexpected. It was very different code but the way that the "OR" was used was the same.
Where am I going wrong? TIA

I just reran your code, and your code works fine. Here is the output =>
Bro, how old are you?18
Bro, what's your favorite food?fish fingers
You're 18 and you eat fish fingers??
That's lame Bro, grow up.
Welcome to Programiz!
Perhaps, you made a typo in your input; or maybe you have put a double space or something. But the || statement is working as it should be.

Related

How do I send data and a string for discord bot?

if(args[0] != undefined){
var SendThing = JSON.stringify(args[0], " was not An Imposter!")
message.channel.send(SendThing)
}
How do I make it so it's like ";eject Person", "Person was not An Imposter!" without it just saying things like "NaN" or ""Person""?
I was told by someone in the comments to do:
if(args[0] != undefined){
message.channel.send(args[0] + " was not An Imposter!")
}else{
message.channel.send("Name someone to eject!")
}
instead of what I tried, this works, and I'm sorry for asking such a dumb question.

HTML: Compare input with a preset value

Simple and stupid question: I want to get a value in HTML and check if it equals a preset value.
If I were to write that in Java, it'd be like this:
if (sc.nextLine().equals("preset")){//sc is a Scanner(System.in) already declared above
//do stuff
}
else{
//do stuff
}
I know near to nothing about HTML and promised I'd have this done for a friend for something in school. It was a stupid move. Now I'm stuck banging my head to my table, reading tutorials and missing something very important.
I know it's a stupid question, but I really need help. I know nothing of html and/or php and any help would be welcome.
Something like this should get you started. (javascript and html - you'll notice that javascript is not strongly typed, so swapping ints, etc. for the string will have a good chance of still working - this is not always a good thing.)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<p id="value">No good deed goes unpunished.</p>
<p id="value2">6</p>
<script>
var preset = "No good deed goes unpunished."
var val = document.getElementById("value");
if (JSON.stringify(val.innerText) == "\"No good deed goes unpunished.\""){
document.write("Kind, not stupid!<br><br>");
}
// Scandalously lifted from another SO answer...
function strcmp(a, b){
return (a < b ? -1 : ( a > b ? 1 : 0 ));
}
var preset2 = 6;
var val2 = document.getElementById("value2");
if(strcmp(preset2, val2) == 0){
document.write("Always kind, but not stupid!");
}
</script>
</body>
</html>

HTML5 input type number not working in firefox

I am using HTML5 input type=number. Its working perfectly in Chrome browser, but its not working in Firefox and IE9.
I want to increment the quantity by one i.e. step=1 and also I have set min=1.
I am using the following code:
<form action="" class="cart" method="post" enctype='multipart/form-data'>
<div class="quantity">
<input type="number" step="1" min="1" name="quantity" value="1" title="Qty" class="input-text qty text" />
</div>
<button type="submit" class="single_add_to_cart_button button alt">Add to cart</button>
</form>
Is there any patch or hack to make it work in Firefox and IE9. Or else, what could be the possible solution for that.
It is not supported in firefox or internet explorer, except for version 11 which has partial support. See this comparison matrix.
You can use the number polyfill shim to get support for unsupported browsers.
Alternately, you can use a textfield with a pattern="" attribute. Although it doesn't have the up and down buttons, it does validate for having the correct values:
<input type="text"
name="quantity"
pattern="[1-9]"
value="1"
required
title="Qty"
class="input-text qty text"
/>
You can alter the pattern to your quantity wishes, it is now set for a value ranging from 1 to 9. Also you can add up/down buttons with JS/jQuery that have hotkeys bound to them for a more number-field-like feel.
For React I have used a simple and clean implementation to forbid letters in Firefox/Safari/Chrome etc...
<input type="number" onKeyDown={(event) => checkIfNumber(event)} />
checkIfNumber(event) {
/**
* Allowing: Integers | Backspace | Tab | Delete | Left & Right arrow keys
**/
const regex = new RegExp(/(^\d*$)|(Backspace|Tab|Delete|ArrowLeft|ArrowRight)/);
return !event.key.match(regex) && event.preventDefault();
}
Allowing more keys:
By logging the event.key in the console you are able to check the actual value of the pressed key while then adding it to the regex using a pipe | symbol.
Keep in mind that this solution only allows Integers, if you want to allow floating numbers(decimals) use the following regex pattern
regex = new RegExp(/(^\d*\.?\d*$)|(Backspace|Tab|Delete|ArrowLeft|ArrowRight)/)
You can build and check your regex pattern here:
https://regex101.com/
The input type number is not supported yet in Firefox or IE9 (almost in IE10), so it will revert to input type text.
See this compatibility chart.
There's really no need for a "patch or hack" - a regular input field will work just fine. That's why it reverts to a text field. Whether or not it displays as an actual number field to the end-user is just a bonus to make it slightly more convenient. You should still be doing server-side checks on whatever value is sent to you, so allowing a user to just type in a number when their browser doesn't support the number type shouldn't harm anything.
It's not supported.
You can use javascript for the same result if you really need it.
There are lot of examples :
Increment value of textinput with jquery like spinner
I am using firefox, I had the same issue developing my input type number typing characters and spaces etc...
anyway I am using angular 2 in this example, it's almost similar to JavaScript, so you can use this code in every case :
here is the html :
<input class="form-control form-control-sm" id="qte" type="number" min="1" max="30" step="1" [(ngModel)]="numberVoucher"
(keypress)="FilterInput($event)" />
here is the function FilterInput :
FilterInput(event: any) {
let numberEntered = false;
if ((event.which >= 48 && event.which <= 57) || (event.which >= 37 && event.which <= 40)) { //input number entered or one of the 4 directtion up, down, left and right
//console.log('input number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
numberEntered = true;
}
else {
//input command entered of delete, backspace or one of the 4 directtion up, down, left and right
if ((event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 46 || event.which == 8) {
//console.log('input command entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
}
else {
//console.log('input not number entered :' + event.which + ' ' + event.keyCode + ' ' + event.charCode);
event.preventDefault();
}
}
// input is not impty
if (this.validForm) {
// a number was typed
if (numberEntered) {
let newNumber = parseInt(this.numberVoucher + '' + String.fromCharCode(event.which));
console.log('new number : ' + newNumber);
// checking the condition of max value
if ((newNumber <= 30 && newNumber >= 1) || Number.isNaN(newNumber)) {
console.log('valid number : ' + newNumber);
}
else {
console.log('max value will not be valid');
event.preventDefault();
}
}
// command of delete or backspace was types
if (event.keyCode == 46 || event.which == 8) {
if (this.numberVoucher >= 1 && this.numberVoucher <= 9) {
console.log('min value will not be valid');
this.numberVoucher = 1;
//event.preventDefault();
this.validForm = true;
}
}
}
// input is empty
else {
console.log('this.validForm = true');
this.validForm = false;
}
};
in this function I had to just let the keypress of numbers, direction, deletes enter.
To allow only number and points to be written in an input we have to get the value of the pressed key and compare it with a REGEX (test() method), otherwise the event isn't executed.
const input = document.getElementById("numberInput");
input.addEventListener("keypress", e => {
// If the input is empty and the key pressed is "0" nothing is printed
if (!e.target.value && e.key == 0) {
e.preventDefault();
} else {
// If the key pressed is not a number or a period, nothing is printed
if (!/[0-9.]/.test(keyValue)) {
e.preventDefault();
}
}
}
Also I created a function that allows writing a maximum of three whole numbers and two decimal numbers.
I hope it helps you.
I usually post information that has helped me or some solutions on my twitter (#PabloAndresValC)
input.addEventListener("keypress", e => {
const keyValue = e.key;
// If the input is empty and the key pressed is "0" nothing is printed
if (!e.target.value && keyValue == 0) {
e.preventDefault();
} else {
// If the key pressed is not a number or a period, nothing is printed
if (!/[0-9.]/.test(keyValue)) {
e.preventDefault();
} else {
// If the number has one or two whole numbers and a point, another
// point won't be printed
if (/[0-9]{1,2}[.]/.test(e.target.value) && keyValue == ".") {
e.preventDefault();
}
// If the number has one or two whole numbers and a point
else if (/[0-9]{1,2}[.]/.test(e.target.value)) {
// We can write up to two more numbers after the point
if (/[0-9]{1,2}[.][0-9]{2}/.test(e.target.value)) {
e.preventDefault();
}
}
// If there are 3 numbers and we press another, a point
// will be printed automatically
// And we can write up to two more numbers after the point
else if (/[0-9]{3}/.test(e.target.value) && keyValue != ".") {
e.target.value += ".";
if (/[0-9]{3}[.][0-9]{2}/.test(e.target.value)) {
e.preventDefault();
}
}
}
}
});
Note: The min attribute of the tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.
Note: The min attribute will not work for dates and time in Internet Explorer 10, since IE 10 does not support these input types.
Source: http://www.w3schools.com/tags/att_input_min.asp
Firefox 89.0 solves this problem.
I think this is the best practice in my previous projects experience.
This solution worked on Firefox, Safari and other not support input[type=number] realized browsers.
document.querySelector('#number-input').addEventListener('keydown', function(evt){
!/(^\d*\.?\d*$)|(Backspace|Control|Meta|a)/.test(evt.key) && evt.preventDefault()
})
<html>
<input type="number" id="number-input"/>
</html>
<input
type="text"
class="form-control"
#keypress="getMobileNumber($event)"
/>
//Function
function:getMobileNumber(e){
let char = String.fromCharCode(e.keyCode); // Get the character
if (/^[0-9]*$/.test(char)) return true;
// Match with regex
else e.preventDefault(); // If not match, don't add to input text
},

CSS: text-transform not working properly for Turkish characters

The implementations of the major browsers seem to have problems with text-transform: uppercase with Turkish characters. As far as I know (I'm not Turkish.) there are four different i characters: ı i I İ where the last two are the uppercase representations of the former two.
However applying text-transform:uppercase to ı i, the browsers (checked IE, Firefox, Chrome and Safari) results in I I which is not correct and may change the meaning of the words so much so that they become insults. (That's what I've been told)
As my research for solutions did not reveal any my question is: Are there workarounds for this issue? The first workaround might be to remove text-transform: uppercase entirely but that's some sort of last resort.
Funny thing, the W3C has tests for this problem on their site, but lack of further information about this issue. http://www.w3.org/International/tests/tests-html-css/tests-text-transform/generate?test=5
I appreciate any help and looking forward to your answers :-)
Here's a codepen
You can add lang attribute and set its value to tr to solve this:
<html lang="tr"> or <div lang="tr">
Here is working example.
Here's a quick and dirty workaround example - it's faster than I thought (tested in a document with 2400 tags -> no delay). But I see that js workarounds are not the very best solution
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-3">
</head>
<body>
<div style="text-transform:uppercase">a b c ç d e f g ğ h ı i j k l m n o ö p r s ş t u ü v y z (source)</div> <div>A B C Ç D E F G Ğ H I İ J K L M N O Ö P R S Ş T U Ü V Y Z (should be like this)</div>
<script>
function getStyle(element, style) {
var result;
if (document.defaultView && document.defaultView.getComputedStyle) {
result = document.defaultView.getComputedStyle(element, '').getPropertyValue(style);
} else if(element.currentStyle) {
style = style.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
result = element.currentStyle[style];
}
return result;
}
function replaceRecursive(element) {
if (element && element.style && getStyle(element, 'text-transform') == 'uppercase') {
element.innerHTML = element.innerHTML.replace(/ı/g, 'I');
element.innerHTML = element.innerHTML.replace(/i/g, 'İ'); // replaces 'i' in tags too, regular expression should be extended if necessary
}
if (!element.childNodes || element.childNodes.length == 0) return;
for (var n in element.childNodes) {
replaceRecursive(element.childNodes[n]);
}
}
window.onload = function() { // as appropriate 'ondomready'
alert('before...');
replaceRecursive(document.getElementsByTagName('body')[0]);
alert('...after');
}
</script>
</body>
</html>
Here's my enhanced version of alex's code that I am using in production:
(function($) {
function getStyle(element, style) {
var result;
if (document.defaultView && document.defaultView.getComputedStyle) {
result = document.defaultView.getComputedStyle(element, '').getPropertyValue(style);
} else if(element.currentStyle) {
style = style.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
result = element.currentStyle[style];
}
return result;
}
function replaceRecursive(element, lang) {
if(element.lang) {
lang = element.lang; // Maintain language context
}
if (element && element.style && getStyle(element, 'text-transform') == 'uppercase') {
if (lang == 'tr' && element.value) {
element.value = element.value.replace(/ı/g, 'I');
element.value = element.value.replace(/i/g, 'İ');
}
for (var i = 0; i < element.childNodes.length; ++i) {
if (lang == 'tr' && element.childNodes[i].nodeType == Node.TEXT_NODE) {
element.childNodes[i].textContent = element.childNodes[i].textContent.replace(/ı/g, 'I');
element.childNodes[i].textContent = element.childNodes[i].textContent.replace(/i/g, 'İ');
} else {
replaceRecursive(element.childNodes[i], lang);
}
}
} else {
if (!element.childNodes || element.childNodes.length == 0) return;
for (var i = 0; i < element.childNodes.length; ++i) {
replaceRecursive(element.childNodes[i], lang);
}
}
}
$(document).ready(function(){ replaceRecursive(document.getElementsByTagName('html')[0], ''); })
})(jQuery);
Note that I am using jQuery here only for the ready() function. The jQuery compatibility wrapper is also as a convenient way to namespace the functions. Other than that, the two functions do not rely on jQuery at all, so you could pull them out.
Compared to alex's original version this one solves a couple problems:
It keeps track of the lang attribute as it recurses through, since if you have mixed Turkish and other latin content you will get improper transforms on the non-Turkish without it. Pursuant to this I pass in the base html element, not the body. You can stick lang="en" on any tag that is not Turkish to prevent improper capitalization.
It applies the transformation only to TEXT_NODES because the previous innerHTML method did not work with mixed text/element nodes such as labels with text and checkboxes inside them.
While having some notable deficiencies compared to a server side solution, it also has some major advantages, the chief of which is guaranteed coverage without the server-side having to be aware of what styles are applied to what content. If any of the content is being indexed and shown in Google summaries (for example) it is much better if it stays lowercase when served.
The next version of Firefox Nightly (which should become Firefox 14) has a fix for this problem and should handle the case without any hack (as the CSS3 specs request it).
The gory details are available in that bug : https://bugzilla.mozilla.org/show_bug.cgi?id=231162
They also fixed the problem for font-variant I think (For those not knowing what font-variant does, see https://developer.mozilla.org/en/CSS/font-variant , not yet up-to-date with the change but the doc is browser-agnostic and a wiki, so...)
The root cause of this problem must be incorrect handling of these turkish characters by unicode library used in all these browsers. So I doubt there is an front-end-side fix for that.
Someone has to report this issue to the developers of these unicode libs, and it would be fixed in few weeks/months.
If you can't rely on text-transform and browsers you will have to render your text in uppercase yourself on the server (hope you're not uppercasing the text as the user types it).
You should have a better support for internationalisation there.
This work-around requires some Javascript. If you don't want to do that, but have something server side that can preprocess the text, this idea will work there too (I think).
First, detect if you are running in Turkish. If you are, then scan whatever you are going to uppercase to see if it contains the problem characters. If they do, replace all of those characters with the uppercase version of them. Then apply the uppercase CSS. Since the problem characters are already uppercase, that should be a totally fine (ghetto) work around. For Javascript, I envision having to deal with some .innerHTML on your impacted elements.
Let me know if you need any implementation details, I have a good idea of how to do this in Javascript using Javascript string manipulation methods. This general idea should get you most of the way there (and hopefully get me a bounty!)
-Brian J. Stinar-

how to filter XML attributes in AS3

Ok- here's a painfully easy one I bet --
I'm aware of how to use EX4 to filter most pieces of the xml I need
however how can I filter an XML list such as the one below to check
say --- if a dog is a beagle? preferably as a Boolean.
var theXml:XML =
<animals>
<animal dog ="poodle" cat="Siamese" />
<animal dog ="beagle" cat="calico" />
<animal dog ="mutt" cat="tabby" />
</animals>
var animalList:XMLList =
theXml.animals.animal;
this ended up working ( thanks Tyler )...
if (theXml.animals.animal.(#dog == "beagle").length > 0) {
trace('match')
}
thanks ! -MW
I love the power of E4X, here's the example of what you are looking for:
theXml.animals.animal.(#dog == 'beagle');
If it finds a match it'll return it.
EDIT
To answere your question below:
var xml:XML = <a id="34"></a>;
//traces
if (xml.(#id == '34').length() != 0) {
trace('match')
}
//no trace
if (xml.(#id == '35').length() != 0) {
trace('match')
}
You shouldn't need the root node "animals":
theXml.animal.(#dog == 'beagle');