does number zero work as " " in javascript? - javascript

document.getElementById("Btn1").onclick = function() {
var aa = document.getElementById("fInput").value;
var a = Number(aa);
var bb = document.getElementById("sInput").value;
var b = Number(bb);
if (a == "" || b == "") {
alert("Fill both inputs");
} else if (a < 1 || a > 3 || b < 1 || b > 3) {
alert(" Fields can only contain values ' 1 & 2 & 3 ' ");
} else if (a == b) {
alert("Not Possible !!");
} else {
var myArray = ['frBox', 'snBox', 'thirdBox'];
var id1 = myArray[a - 1];
var id2 = myArray[b - 1];
Swap(id1, id2);
}
}
function Swap(id1, id2) {
var x = document.getElementById(id1).innerHTML;
var y = document.getElementById(id2).innerHTML;
document.getElementById(id1).innerHTML = y;
document.getElementById(id2).innerHTML = x;
}
.fBox {
height: 100px;
width: auto;
background-color: yellow;
color: green;
}
.sBox {
height: 100px;
width: auto;
background-color: aqua;
color: black;
}
.thBox {
height: 100px;
width: auto;
background-color: rgba(23, 84, 244, 0.4);
color: rgb(45, 65, 77);
}
button {
height: auto;
width: 150px;
text-align: center;
background-color: crimson;
color: white;
border-radius: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
<div class="fBox" id="frBox">
<p>
Hello From the first box.
</p>
</div>
<div class="sBox" id="snBox">
<p>
JavaScript is Cool !!!
</p>
</div>
<div class="thBox" id="thirdBox">
<p>
I am Learning JavaScript !!!
</p>
</div><br>
<input id="fInput" placeholder="Num 1">
<input id="sInput" placeholder="Num 2"><br><br>
<button id="Btn1"> Click to Swap </button>
</body>
</html>
When I enter 0 in any of the inputs and a number between 1 and 3 in the other input and click on the button, it alerts "Fill both inputs".
But I expected seeing " Fields can only contain values ' 1 & 2 & 3 ' " alert.
or when I fill both inputs with 0, this issue again happens!!
Does 0 work as "" in JavaScript or there is a problem in my code??

0 and "" both evaluate to false in Javascript.
var x = 0;
if (x) {
console.log('Will not be called.');
}
var y = '';
if (y) {
console.log('Will not be called.');
}
As some of the other answers have alluded to, there is also lazy vs strict equality, using == vs ===.
That wont fix your problem though, because you're doing var a = Number(aa);. If you enter 0 in one of your inputs, you'll get Number(0), which is 0. If you don't enter anything in one of your inputs, you'll get Number(''), which is 0.
I'd replace
if (a == "" || b == "") { ... }
with
if (!a || !b) { ... }
// shorthand version of (if a === false || b === false)
// which will be the case if a or b === 0
If 0 is entered in either input, or if either input is left empty, you'll end up with a or b being 0, which will evaluate to false.

Shortly:
If you use ==, yes.
To avoid it, use ===.
Longer:
== (double equals) does some weird things because
it tries to transform values to same types (in this case, to numbers), and
Number("") === 0
Conclusion:
It's better to use Strict equality operator (===) instead:
document.getElementById("Btn1").onclick = function() {
var aa = document.getElementById("fInput").value;
var a = Number(aa);
var bb = document.getElementById("sInput").value;
var b = Number(bb);
if (aa===""||bb==="") {
alert("Fill both inputs");
} else if (a < 1 || a > 3 || b < 1 || b > 3) {
alert(" Fields can only contain values ' 1 & 2 & 3 ' ");
} else if (a == b) {
alert("Not Possible !!");
} else {
var myArray = ['frBox', 'snBox', 'thirdBox'];
var id1 = myArray[a - 1];
var id2 = myArray[b - 1];
Swap(id1, id2);
}
}
function Swap(id1, id2) {
var x = document.getElementById(id1).innerHTML;
var y = document.getElementById(id2).innerHTML;
document.getElementById(id1).innerHTML = y;
document.getElementById(id2).innerHTML = x;
}
.fBox {
height: 100px;
width: auto;
background-color: yellow;
color: green;
}
.sBox {
height: 100px;
width: auto;
background-color: aqua;
color: black;
}
.thBox {
height: 100px;
width: auto;
background-color: rgba(23, 84, 244, 0.4);
color: rgb(45, 65, 77);
}
button {
height: auto;
width: 150px;
text-align: center;
background-color: crimson;
color: white;
border-radius: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
<div class="fBox" id="frBox">
<p>
Hello From the first box.
</p>
</div>
<div class="sBox" id="snBox">
<p>
JavaScript is Cool !!!
</p>
</div>
<div class="thBox" id="thirdBox">
<p>
I am Learning JavaScript !!!
</p>
</div><br>
<input id="fInput" placeholder="Num 1">
<input id="sInput" placeholder="Num 2"><br><br>
<button id="Btn1"> Click to Swap </button>
</body>
</html>
See more information
Comparision of comparision operators
==
===

Related

How to change the font color of an user input value (prompt) in JavaScript?

How can I change the color of the value of the variable number (nb)? How can I change the font color of an user input value (prompt) in JavaScript?
<html>
<head>
<style>
#block{
color: white;
width: 300px;
height: 60px;
background-color: #2b2e2e;
text-align: center;
padding-top: 30px;
}
</style>
</head>
<body>
<div id="block">
</div>
<script>
window.onload = function printNumber(){
var unBlock = document.getElementById("block");
var nb = Number(prompt("Saisir un nombre: "));
if(nb == null || nb == ""){
unBlock.innerHTML = "No input number.";
}else{
unBlock.innerHTML = "Your input number is "+nb;
}
}
</script>
</body>
</html>
The code below illustrates two ways.
By creating a span with colored as its class, it turns it blue.
Subsequently, in my code, I'm overriding that by turning it red using javascript.
Either of those methods will work, but you only need one, not both. I used both just for illustration of your options.
window.onload = function printNumber() {
var unBlock = document.getElementById("block");
var nb = Number(prompt("Saisir un nombre: "));
if (nb == null || nb == "") {
unBlock.innerHTML = "No input number.";
} else {
unBlock.innerHTML = `Your input number is <span class='colored'>${nb}</span>`;
//the next line will select your span and override blue with red.
document.querySelector("span.colored").style.color = 'red';
}
}
#block {
color: white;
width: 300px;
height: 60px;
background-color: #2b2e2e;
text-align: center;
padding-top: 30px;
}
span.colored {
color: blue;
}
<div id="block">
</div>

i want to call a function many time inside my code?

I plan to make this box move every time I click a button
but the problem is that it works first time when I click s or d but does not work after that.
So can any one help me to find the solution to my problem?
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
left: 10px;
top: 20px;
width: 20px;
height: 20px;
background-color: black;
border: 1px solid black;
border-radius: 5px;
}
</style>
</head>
<body id="bd">
<div class="box"></div>
<script >
document.getElementById('bd').addEventListener('keypress', show);
function show(e){
let x = e.which;
if(x == 122){
// 122 = z
document.getElementsByClassName('box')[0].style.top -='50px' ;
}
else if(x == 133){
// 122 = q
document.getElementsByClassName('box')[0].style.left -='50px' ;
}
else if(x == 115){
// 122 = s
document.getElementsByClassName('box')[0].style.top +='50px' ;
}
else if(x == 100){
// // 122 = d
document.getElementsByClassName('box')[0].style.left +='50px' ;
}
}
</script>
</body>
</html>
You are trying to perform operation on string. First need to convert in number.
Sample:
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
left: 10px;
top: 20px;
width: 20px;
height: 20px;
background-color: black;
border: 1px solid black;
border-radius: 5px;
}
</style>
</head>
<body id="bd">
<div class="box"></div>
<script>
const number = (num) => Number(num.split('px')[0])
const addBy50 = (num) => `${number(num) + 50}px`
const subtractBy50 = (num) => `${number(num) - 50}px`
const style = document.getElementsByClassName("box")[0].style
document.addEventListener("keypress", (e) => {
let x = e.which;
const {
top,
left
} = style
switch (e.which) {
case 122:
style.top = subtractBy50(top);
break;
case 113:
style.left = subtractBy50(left);
break
case 115:
style.top = addBy50(top);
break
case 100:
style.left = addBy50(left);
break
}
});
</script>
</body>
</html>
element.style.top and element.style.left are strings, so your statements are essentially saying
element.style.top = "20px" + "50px";
Instead, consider a separate variable storing position:
let positionLeft = 20;
...
if(x == 115){
positionLeft += 50;
document.getElementsByClassName('box')[0].style.top = positionLeft + 'px';
}

Textarea which counting entered symbolys

function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
// var last2 = 100 - integer2;
if (symbolCount >= 100) {
document.querySelector('.hidden_block').style.color = 'green';
}
else if (symbolCount <= 100) {
document.querySelector('.hidden_block').style.color = 'black';
document.querySelector('.error').style.display = "block";
}
else {
document.getElementById('max').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
email.addEventListener("click", function(){
document.querySelector('.hidden_block').style.display = 'block';
document.getElementById('max').style.display = 'none';
});
#max, #max2 {
text-align: right;
margin-right: 55px;
}
.hidden_block {
display: none;
text-align: right;
margin-right: 55px;
}
.error {
display: none;
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<label for="email">Positive</label>
<textarea type="email" class="form-control" id="email" oninput="someFunc()" placeholder="Tell people about your experience: describe the place or activity, recommendations for travelers?"></textarea>
<p id="max">Minimal length - symbols</p>
<div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (minimum:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long. Adding details really helps travelers.</span>
Hi everyone.I have a that simple textarea field.I need to realize something like that.When u write less than 100 words and click the outside of the email id the border color must be red.And error class must displayed.And i need to if the textarea field is empty the tag p with id max must be display block if the user will write any symbol the id max must bu display none.Thanks for help
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
var integerValue = document.getElementById('email');
var hidden_block = document.querySelector('.hidden_block');
var max = document.getElementById('max');
var error = document.querySelector('.error');
var positive = document.getElementById("positive");
// var last2 = 100 - integer2;
if (integer >= 1) {
hidden_block.style.display = 'inline-block';
max.style.display = 'none';
integerValue.classList.add("form-control");
} else {
hidden_block.style.display = 'none';
max.style.display = 'block';
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
}
integerValue.addEventListener("click", function(){
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
});
//Red error and border
document.body.addEventListener("click", function(e) {
var target = e.target || e.srcElement;
if (target !== integerValue && !isChildOf(target, integerValue)) {
error.style.display = "inline-block";
integerValue.classList.add("form-redBorder");
positive.style.color = "red";
} if (integer >= 100) {
error.style.display = "none";
integerValue.classList.remove("form-redBorder");
positive.style.color = "#002C38";
}
}, false);
function isChildOf(child, parent) {
if (child.parentNode === parent) {
return true;
} else if (child.parentNode === null) {
return false;
} else {
return isChildOf(child.parentNode, parent);
}
}
//Finished Red error and border
//Start to count symbols
if (symbolCount >= 100) {
hidden_block.style.color = 'green';
}
else if (symbolCount <= 100) {
hidden_block.style.color = 'black';
}
else {
max.style.color = 'black';
// document.getElementById('max2').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
#email {
display: block;
padding: 6px 12px;
margin: 0 auto;
width: 90% !important;
height: 120px !important;
/*border:1px solid #44A1B7 !important;*/
}
.form-control {
margin: 0 auto;
width: 90% !important;
height: 120px !important;
border:1px solid #44A1B7;
}
#positive, #negative {
padding: 14px 15px 1px 55px;
color: #002C38;
font-size: 18px;
}
.form-redBorder {
margin: 0 auto;
border:1px solid #FF0000 !important;
}
#max, #max2 {
position: absolute;
right: 1%;
margin-right: 55px;
}
.hidden_block {
position: absolute;
right: 1%;
display: none;
text-align: right;
margin-right: 55px;
}
.error {
margin-left: 55px;
display: none;
color: #FF0000;
}
<form role="form">
<div class="form-group">
<p class="help-block">About youre site.</p>
<label for="email" id="positive">Positive</label>
<textarea type="email" id="email" oninput="someFunc()" placeholder="Your review must be at least 100 characters long<br> Adding details really helps travelers"></textarea>
<p id="max">(100 character minimum)</p><div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (min:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long.<br> Adding details really helps travelers..</span>
</div>
</form>

checkbox works only after second click after search

I'm trying to create list of suppliers (checkboxes + labels) and search field to filter suppliers. I managed to get list renderered and after first load it works fine, but after I search through supplier list first click on checkbox doesn't work. I need to click twice for checkbox to become checked.
screenshot
I need checkbox to become checked after first click when searching through supplier list. Please help.
I created this fiddle here
HTML:
<div class="col-sm-12">
<div class="infoBlock suppliersWrapper">
<div class="blockTitle">Supplier:</div>
<div class="blockContent">
<p class="checkedSupliersTitile">Supplier list:</p>
<div class="row">
<div class="col-sm-12 col-lg-8">
<input type="text" class="form-control stickTop" placeholder="Search..." id="SearchSupplierInput">
<ul class="supplierList scrollable" id="suppliers"></ul>
</div>
<div class="col-sm-12 col-lg-4">
<p class="checkedSupliersTitile">Checked suppliers:</p>
<p class="checkedSupliersText" id="checkedSuppliers">no suppliers selected</p>
</div>
</div>
</div>
</div>
</div>
CSS:
.supplierList label {
color: #575757;
display: block;
font-size: 15px;
font-weight: 400;
cursor:pointer;
font-family: 'Ubuntu', sans-serif;
}
.supplierList input[type="checkbox" ]{
width : 2em;
margin : 0;
padding : 0;
font-size : 1em;
opacity : 0;
}
.supplierList input[type="checkbox" ] + label{
display : inline-block;
margin-left : -1em;
line-height : 1.5em;
position:relative;
z-index: 33;
}
.supplierList input[type="checkbox"] + label::before {
border: 1px solid #d6d6d6;
border-radius: 1px;
content: "";
height: 20px;
left: -1.8em;
position: absolute;
top: 0.06em;
width: 20px;
-webkit-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
-moz-box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
box-shadow: 3px 3px 0 0 rgba(25, 24, 25, 0.04) inset;
background: #ffffff;
}
.supplierList input[type="checkbox" ]:checked + label:before{
background:#46c87c;
}
.supplierList input[type="checkbox"]:checked + label::after {
color: #fff;
content: "";
font-family: "fontawesome";
left: -1.6em;
position: absolute;
top: 0;
}
JavaScript:
$(document).ready(function() {
var SupplierList = [{"name":"125","id":"1"},
{"name":"2Bit Telecom Corporation","id":"2"},
{"name":"Alleven Telecom Corp Standart","id":"3"}];
var selectedSuppliers = [];
// Собираем и фильтруем активных поставшиков
renderSupplierList(SupplierList);
$("#SearchSupplierInput").on("change paste keyup", function() {
var userInput = $(this).val();
var my_json = JSON.stringify(SupplierList);
var filtered_supplierList = find_in_object(JSON.parse(my_json), {name:userInput});
if (userInput.length >= 3) {
$("#suppliers").html("");
renderSupplierList(filtered_supplierList);
} else if(!userInput) {
$("#suppliers").html("");
renderSupplierList(SupplierList);
}
});
function renderSupplierList(array) {
array.forEach(function(item, i) {
if(typeof selectedSuppliers["id"+item.id] === 'undefined') {
var ifCheckd = "";
}
else {
var ifCheckd = "checked";
}
$("#suppliers").append('\
<li><span>\n\
<input class="supplierSelect" type="checkbox" id="supplier'+i+'" ' + ifCheckd + ' name="supplier" value="'+ item.id +'"> \n\
<label for="supplier'+i+'">'+ item.name +'</label>\n\
</span></li>');
});
}
function find_in_object(my_object, my_criteria) {
return my_object.filter(function(obj) {
//console.log(obj);
return Object.keys(my_criteria).every(function(c) {
//if (obj[c].search(/my_criteria[c]/i) == -1) {
if (obj[c].search(new RegExp(my_criteria[c], "i")) == -1) {
return false;
} else {
return true;
}
});
});
}
$('.supplierList').on('change', 'input[type=checkbox]', function() {
supplierCheckboxChange(this);
});
function sortSingle(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function supplierCheckboxChange(currEl) {
var cText = $( currEl ).siblings("label").text();
var cID = "id" + currEl.value;
if(currEl.checked) {
selectedSuppliers[cID] = cText;
}
else {
delete selectedSuppliers[cID];
}
var tmpSuppl = [];
for (var key in selectedSuppliers) {
tmpSuppl.push(selectedSuppliers[key]);
}
tmpSuppl.sort(function(a, b) {
var x = a.toLowerCase(); var y = b.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var suppliers = tmpSuppl.join(', ');
if (!suppliers) {
suppliers = "no suppliers selected";
}
$('#checkedSuppliers').text(suppliers);
}
});
This happens because your renderList function is being called more than once. First keyup is triggered when you press a key and then when text box looses focus(when you click on checkbox) change is triggered.
This causes your renderList method to get executed twice and the checked checkbox gets replace by a new checkbox.
To fix this, just change
$("#SearchSupplierInput").on("change paste keyup", function() { ... }
To
$("#SearchSupplierInput").on("paste keyup", function() { ... }
Have a look at this fiddle and check the console. https://jsfiddle.net/nh7u4Lck/2/

Missing word game (gap filler)

i am making a little word game where theres a missing word and if you fill in the input field with the correct answer it turns green
I would like to add a functionality to this code but I am not sure how
I want to edit it so if you put a wrong answer in it turns red
at the minute it just adds up your score and turns green if you put in the right answer
i know the answer is to do with the end of the js file where it turns it green if correct
this is the html
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'> </script>
<script type="text/javascript">
$(document).ready(function(){
$("input").not( $(":button") ).keypress(function (evt) {
if (evt.keyCode == 13) {
iname = $(this).val();
if (iname !== 'Submit'){
var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false
}
}
});
});</script>
<script type="text/javascript" src="prolinguis-gap-filler.js"></script>
<div style="font-family:Helvetica; font-size: 18px; vertical-align:bottom; color:#3e2e41; margin:16px 0;"> Score: <label id="label_score">0%</label></div>
<form class="game-form" style="padding: 0px; width: 100%; margin: 10px auto;" >
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 1</p>
<p>Where is Stephen from? <input TYPE="text" id="ctr1" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 2</p>
<p>If someone asks you, what’s cooking? You shouldn’t answer with: <input TYPE="text" id="ctr2" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////// -->
<div class="game-hold" style=" width: 100%; text-align: left; display: inline-block;">
<p style="font-size: 14px; font-weight: bold; margin: 5px 0; color: #333333;">Question 3</p>
<p>Instead, just say <input TYPE="text" id="ctr3" onBlur="validate(this.value, this.id)" style="text-transform: uppercase; font-family:Helvetica; font-size: 10px; width:150px; height:18px; text-align: left; color:#000000;"></input></p>
</div>
</form>
and in a js file i have this
<script>
var ctr = 0
var score_ctr = 0
function validate(value, id) {
if (id =='ctr1' && (value.toUpperCase()=="UNITED STATES" || value.toUpperCase()=="USA" || value.toUpperCase()=="AMERICA")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="UNITED STATES";
}
if (id =='ctr2' && (value.toUpperCase()=="GOOD")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="GOOD";
}
if (id =='ctr3' && (value.toUpperCase()=="NOTHING MUCH" || value.toUpperCase()=="NOT MUCH")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value="NOTHING MUCH";
}
}
function correct_answer (id) {
score_ctr = (ctr * 100) / 3
document.getElementById('label_score').innerHTML = score_ctr.toFixed(0) + '%'
document.getElementById(id).disabled=true;
document.getElementById(id).style.backgroundColor = '#c1d82f'
document.getElementById(id).style.cursor="default"
}
</script>
Change validate(value, id) to the following:
function validate(value, id) {
if (id == 'ctr1' && (value.toUpperCase() == "UNITED STATES" || value.toUpperCase() == "USA" || value.toUpperCase() == "AMERICA")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "UNITED STATES";
}
else if (id == 'ctr2' && (value.toUpperCase() == "GOOD")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "GOOD";
}
else if (id == 'ctr3' && (value.toUpperCase() == "NOTHING MUCH" || value.toUpperCase() == "NOT MUCH")) {
ctr = ctr + 1;
correct_answer(id);
document.getElementById(id).value = "NOTHING MUCH";
}
else
{
document.getElementById(id).style.backgroundColor = '#ff0000';
document.getElementById(id).style.cursor = "default";
}
This will go through and check all the different input fields, and if no correct answer is found, will set the background of the last blurred field to red.
Just a hint, if you want to clean up your code a bit, consider using a switch statement to determine which id you're checking.

Categories

Resources