Javascript switch statement? - javascript

I have some code like below:
for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;
if (option == "A") {
$scope.aSelected = true;
break;
}
}
for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;
if (option == "B") {
$scope.bSelected = true;
break;
}
}
Is it possible to right this in a switch statement like below:
for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;
switch (option) {
case "A":
$scope.aSelected = true;
break;
case "B":
$scope.bSelected = true;
break;
default:
console.log('unrecognized option');
}
}
Is this actually incorrect in the switch case because the first option may be A which will break out of the loop and then for example if 'B' was the option in a later position of the collection it would never get bSelected = true;

It's correct because the BREAK inside of SWITCH will break out of it, not the whole FOR loop, and therefore it will check for B too.

Related

How to register/unregister events in a dynamic way, using Vanilla JS

I've spoken to my teacher and he told me that the reason why you would place the <script> element as last part of <body>, use onload= event directly on HTML-element, or in another way include the script in <body> (or deferring its execution), is because you want to guarantee that the script will only be activated once the DOM has been loaded, and the needed elements can be accessed. But... this is not the convention since it will be very difficult to scale in a solution where multiple HTML-documents are involved, sharing the same file resources such as JavaScript in this case. Instead, you'll handle this flow of execution by registering events properly using JS.
I've been told to put the Window Event load at the end my of JS file.
These are the error I get in booking.html: Uncaught TypeError: Cannot read property 'target' of undefined at addEvent (main.js:65) at start (main.js:10) addEvent.
Why do I get this error?
Here is my code:
function start() {
let path = window.location.pathname;
if (path.endsWith("contact.html")) {
browserDetection;
} else if (path.endsWith("employees.html") || path.endsWith("ourfleet.html")) {
registerGalleryEvents();
} else if (path.endsWith("booking.html")) {
addEvent();
getSeat();
}
/* browser detector */
var browserDetection = (function (agent) {
switch (true) {
case agent.indexOf("edge") > -1:
return "MS Edge (EdgeHtml)";
case agent.indexOf("edg") > -1:
return "Microsoft Edge";
case agent.indexOf("opr") > -1 && !!window.opr:
return "Opera";
case agent.indexOf("chrome") > -1 && !!window.chrome:
return "Chrome";
case agent.indexOf("trident") > -1:
return "Internet Explorer";
case agent.indexOf("firefox") > -1:
return "Mozilla Firefox";
case agent.indexOf("safari") > -1:
return "Safari";
default:
return "other";
}
})(window.navigator.userAgent.toLowerCase());
document.getElementById("specific-h3").innerHTML = "Here you can contact us if you have any questions. <br>\ <br>\ And by the way, you are using " + browserDetection + " browser.";
function registerGalleryEvents() {
const galleryImgs = document.querySelectorAll(".galleryImg");
galleryImgs.forEach((galleryImg) => {
galleryImg.addEventListener("click", () => {
displayImage(galleryImg);
});
});
}
//declaring the displayImage function. reference: https://stackoverflow.com/a/65974064/14502646
function displayImage(thumbnail) {
const currentImgSrc = thumbnail.getAttribute("src");
const [imgName, ext] = currentImgSrc.split(".");
document.getElementById('myPicture').src = imgName + '-big.' + ext;
}
var seats = document.getElementsByClassName('grid-item')
// Saving Javascript objects in sessionsStorage.
var data = JSON.parse(sessionStorage.getItem('bookingData'))
function addEvent(event) {
//Makes sure that the first 6 seats are Business class and the rest are Economy.
if (parseInt(event.target.innerHTML) >= 1 && parseInt(event.target.innerHTML) <= 6) {
document.getElementById('classType').innerHTML = 'Class Type: Business'
} else {
document.getElementById('classType').innerHTML = 'Class Type: Economy'
}
//event.target.innerHTML is the number of seat that is selected.
document.getElementById('seat').innerHTML = 'Seat Selected: ' + event.target.innerHTML
document.getElementById('seatNumber').value = event.target.innerHTML
var selectedSeats = document.getElementsByClassName("selected");
if (selectedSeats.length > 0) {
for (var j = 0; j < selectedSeats.length; j++) {
selectedSeats.item(j).className = selectedSeats.item(j).className.replace('grid-item selected', 'grid-item');
}
}
event.target.className = event.target.className + " selected";
}
for (var i = 0; i < seats.length; i++) {
seats[i].addEventListener('click', addEvent)
}
var seatList = document.getElementsByClassName("grid-item")
for (var i = 0; i < data.length; i++) {
seatList.item(parseInt(data[i].seatNo) - 1).removeEventListener("click", addEvent)
seatList.item(parseInt(data[i].seatNo) - 1).className = seatList.item(parseInt(data[i].seatNo) - 1).className.replace('grid-item', 'grid-item booked')
}
document.getElementsByClassName('reset').addEventListener('click', function () {
location.reload()
})
function getSeat() {
var inp = document.getElementsByClassName("grid-item selected");
if (inp.length > 0) {
var inputData = {
firstName: document.getElementById('fname').value,
lastName: document.getElementById('lname').value,
identityNo: document.getElementById('identity').value,
classType: document.getElementById('classType').innerHTML,
seatNo: parseInt(document.getElementById('seatNumber').value)
}
if (JSON.parse(sessionStorage.getItem('bookingData')) != null) {
var bookingData = JSON.parse(sessionStorage.getItem('bookingData'))
bookingData.push(inputData)
sessionStorage.setItem('bookingData', JSON.stringify(bookingData))
} else {
console.log('block')
var bookingData = []
bookingData.push(inputData)
sessionStorage.setItem('bookingData', JSON.stringify(bookingData))
}
alert('Flight booked successfully.')
window.print()
} else {
alert("Select a seat before proceeding!")
}
}
}
window.addEventListener("load", start);

how i get out from the loop if switch case implemented(there is a switch inside the loop)

How I get out from the loop if switch-case implemented (there is a switch inside the loop).
function playInbestPlace() {
console.log("hello from playInbestPlace ")
findEmptyarea();
for (var i = 0; i < indexOfEmpty.length; i++) {
var elem = indexOfEmpty[i];
switch (elem) {
case 0:
cells[elem].childNodes[0].append("o");
break;
case 2:
cells[elem].childNodes[0].append("o");
break;
case 4:
cells[elem].childNodes[0].append("o");
break;
case 6:
cells[elem].childNodes[0].append("o");
break;
case 8:
cells[elem].childNodes[0].append("o");
break;
}
}
}
I want it to get out if any case valid.
you can add a variable found and break out of the loop if it's true :
function playInbestPlace() {
console.log("hello from playInbestPlace ")
findEmptyarea();
for (var i = 0; i < indexOfEmpty.length; i++) {
var elem = indexOfEmpty[i];
var found = false; // initial found is false
switch (elem) {
case 0:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 2:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 4:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 6:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 8:
cells[elem].childNodes[0].append("o");
found = true;
break;
}
if(found) // break out if it's true
break;
}
}
You could use a flag variable to break from the loop when some condition is verified.
function playInbestPlace() {
console.log("hello from playInbestPlace ");
findEmptyarea();
var keepOnLooping = true;
for (var i = 0; keepOnLooping && i < indexOfEmpty.length; i++) {
if (elem % 2 === 0) {
cells[elem].childNodes[0].append("o");
keepOnLooping = false;
}
}
}
I've also added epascarello optimization in my answer.

change current TextArea value without assign a new one?

When I press "A" to add a character to a value of the TextArea, how does the value change?
does the browser do something like this:
texarea.value+="A";
//same as:
texarea.value=texarea.value+"A";
?
I would like to change that value dynamicaly and notify the textarea about the change without assign a new one, because I think that assingment is not very perfomant if the value takes a lot of memory.
Is there a way to do this?
Ok, I solved it:
at first sight this solution seems also not very performant, but it has some big advatages:
for example you could load only a specific part of a very big file from server and dynamically load it if the user scroll through the page.
you can also update the client version of the file representation (synchronized editing)
document.registerElement('text-area', class NicePanel extends HTMLElement {
createdCallback() {
//this.root = this.createShadowRoot();
this.tabIndex = 1;
this.onkeydown = function(e) {
this.monkeydown(e);
}
this.onkeypress = function(e) {
this.monkeypress(e);
}
this.setValue(this.innerHTML);
}
setValue(value) {
var mutablestring = Array.from(value);
this.innerHTML = "";
var l = mutablestring.length;
for (var i = 0; i < l; i++) {
if (mutablestring[i] == '\n') {
var br = document.createElement('br');
br.onclick = this.characterClick;
this.appendChild(br);
} else {
var span = document.createElement('span');
span.onclick = this.characterClick;
span.innerHTML = mutablestring[i];
this.appendChild(span);
}
}
this.cursor = document.createElement('span');
this.cursor.innerHTML = "|";
this.appendChild(this.cursor);
}
getValue() {
var value = "";
var children = this.childNodes;
var that = this;
children.forEach(function(child) {
if (child.nodeName == "BR") {
value += "\n";
return;
}
if (child === that.cursor) return;
value += child.innerHTML;
});
return value;
}
attachedCallback() {}
monkeydown(e) {
var KeyID = event.keyCode;
switch (KeyID) {
case 8:
this.cursor.parentNode.removeChild(this.cursor.previousSibling);
e.preventDefault();
break;
case 46:
this.cursor.parentNode.removeChild(this.cursor.nextSibling);
e.preventDefault();
break;
case 13:
var br = document.createElement('br');
br.onclick = this.characterClick;
this.cursor.before(br);
e.preventDefault();
break;
case 37: //left
this.cursor.parentNode.insertBefore(this.cursor, this.cursor.previousSibling);
break;
case 38: //up
break;
case 39: //right
this.cursor.parentNode.insertBefore(this.cursor, this.cursor.nextSibling.nextSibling);
break;
case 40: //down
break;
default:
break;
}
}
characterClick(e) {
this.parentNode.cursor.parentNode.insertBefore(this.parentNode.cursor, e.target);
}
monkeypress(e) {
var span = document.createElement('span');
span.onclick = this.characterClick;
span.innerHTML = String.fromCharCode(e.which);
this.cursor.parentNode.insertBefore(span, this.cursor);
}
monclick(e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== this) {
target = target.parentNode; // If the clicked element isn't a direct child
if (!target) {
return;
} // If element doesn't exist
}
if (target.tagName === 'SPAN') {
alert(target.id); // Check if the element is a LI
}
}
})
var myta = document.getElementById('myta');
myta.setValue("huhu\nlala");
console.log(myta.getValue());
text-area {
width: 100%;
background: #fff;
display: block;
}
<text-area id="myta" class="text">Hello World
</text-area>

what is wrong with .this. javascript if else code?

it works if i use the first half only but i need to widen the parameters
//document.querySelectorAll('font[color="black"]');
var fonts = document.querySelectorAll('font[color="black"]');
var searchString = 'Mir';
var searchString2 = 'MirrorCreator';
for (var i = 0; i < fonts.length; i++) {
var font = fonts[i];
if (fonts[i].innerHTML.indexOf(searchString) !== - 1) {
//alert('Match');
var eventLink = 'ComeHere';
var elA = document.createElement('a');
elA.setAttribute('id', eventLink);
elA.setAttribute('name', eventLink);
font.appendChild(elA);
window.location.hash = 'ComeHere';
break;
}
else (fonts[i].innerHTML.indexOf(searchString2) !== - 1) {
//alert('Match');
var eventLink2 = 'ComeHere2';
var elA2 = document.createElement('a');
elA2.setAttribute('id', eventLink2);
elA2.setAttribute('name', eventLink2);
font.appendChild(elA2);
window.location.hash = 'ComeHere2';
break;
}
}
Here you have wrong syntax:
else (fonts[i].innerHTML.indexOf(searchString2) !== - 1) {
It should be simple
else {
or
else if (fonts[i].innerHTML.indexOf(searchString2) !== - 1) {
You need to change your if else statement.
if(// conditional)
{
// do something.
}
else if(// conditional){
// do something....
}
Your else needs to be else if, because else isn't expecting (fonts[i].innerHTML.indexOf(searchString2) !== - 1)

Only property checked of first radio button works correctly

I am not able to find out why in a function, only if(radioBtn.checked) of the first radio button out of four passes the if. When I log the others, they are still checked when they need to, but the if doesn't seem to work. Here is what I am talking about:
var input = document.getElementsByName("focus");
for(var i = 0; i<input.length; i++) {
input[i].addEventListener("change", function(){
getCheckedRadioValue("focus");
}, false);
}
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
this.value = 0;
for (i=0; i < rads.length; i++) {
console.log(rads[3].checked);
if (rads[i].checked){
this.value = rads[i].value;
console.log(this.value);
return rads[i].value
}
return {
value: this.value
}
}
}
document.addEventListener('keydown', function (event) {
if (event.keyCode == 38) {
console.log(value);
switch (value) {
case "car": car.accelerate(); break;
case "boat": boat.accelerate(); break;
case "aircraft": aircraft.accelerate(); break;
case "amphibia": console.log("amphibia"); break;
default: console.log("Nothing is checked!"); break;
}
}
});
Here is everything in jsfiddle.
You return a value after the first iteration of the for-loop. Simply move the default return outside the for-loop like this:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName), i;
this.value = 0;
for (i = 0; i < rads.length; i++) {
if (rads[i].checked) {
this.value = rads[i].value;
return rads[i].value
}
}
return {
value: this.value
}
}

Categories