Javascript Switch Case Not Working in socialengine - javascript

I am feeling a bit embarrassed to ask this silly question but somehow the following code is not working. The values (bed,room,floor) are fetched right but switch case not working.But the same snippet of switch case code works well in jsfiddle.I m sure I m missing something silly.I m using this in socialengine with mootools enabled
I also want to know how to get an element which has id=roomtype and which is inside a div whose class=form-elements but id=roomtype is not direct child of div class=form-elements.
I can get it by $$('.form-elements #roomtype').get('value') but this refers all elements with #roomtype, this $('.form-elements #roomtype').get('value') doesnt work
<script type="text/javascript">
var updatePrice=function()
{
var room= $$('.form-elements #roomtype').get('value') ;
// alert (room) gets AirCon or Dorm
var price;
switch (room)
{
case "AirCon":
price="10000"; alert("AirCon");
break;
case 'Dorm':
price="5000"; alert("Dorm");
break;
default:
price="00";
}
}
en4.core.runonce.add(updatePrice);// this add this function to DOM Ready
</script>

#1
ID's must be unique.
In MooTools you can do $('roomtype') to get the element with the ID roomtype.
You can also use document.id('roomtype') or even $$('#roomtype').
Since ID's must be unique it's irrelevant the parent of that element, because there is only one.
#2
Note that $ and $$ are different element methods in mootools. $$ takes a CSS selector and returns a collection/array.
$$('#roomtype').get('value'); // returns ['the value']
$('roomtype').get('value'); // return 'the value'
#3
The other problem I see is that you define the price inside the scope of updatePrice() function, so doing price = 5000 inside the switch will not leave the function's scope anyway. You might want to define the var price outside the function, or make the function return that value lie this:
// ...
switch (room) {
case "AirCon":
price = "10000";
alert("AirCon");
break;
case 'Dorm':
price = "5000";
alert("Dorm");
break;
default:
price = "00";
}
return price; // here
}
If you update your fiddle with HTML it will be easier to help you more.
P.s: You are always welcome to ask questions. No need to feel embarrassed.

Related

javascript: avoding if else with javascript object when pattern matching is involved

I am basically trying to avoid branching. I will explain my doubt with the code:
My code is like:
name = "any_random_name_generated_dynamically"
//If else conditions
// foo and bar are the part of the name not the complete name
if (name.match('foo_pattern')) {
"do_thing_1"
}
else if (name.match('bar_pattern')) {
"do_thing_2"
}
else {
"do_thing_3"
}
Is there anyway I can avoid this using javascript objects? Or there any other way to do where less branching is involved.
I tried googling it bu didn't find anything for this particular issue.
You could create a resolve table:
var resolve=[
["Some pattern",function(){alert("wohoo");}],
...
["",function(){alert("default")}]
];
So now you can simply iterate through the table, and find the first pattern that matches, and execute its related function:
var name="somestring";
resolve.find(el=>name.match(el[0]))[1]();
Note that this will crash if no pattern is found, so take care to add a default one.
Alternatively you could use a switch (still ugly):
switch(true){
case name.match("sth") :
dosth();
break;
default:
dodefault();
break;
}

how to put a switch in a variable in javascript?

I'm making a little mini game and I have to put multiple switches inside of themselves, so I really need to know how to put a switch into a few words so I can make this game. I have tried it so that it's fully written out but it takes FOREVER and it is very confusing as to what is what. please help!
EDIT: im sorry i made this so confusing... let me say that again in english (: what i need to do is make it so when they either choose one of the cases or if they choose none of them (default) it would reactivate the switch. the way the person would choose is through a prompt. so what i thought i could do was make a switch into a variable then use that variable inside the switch basicly creating an endless thing that if they choose default it asks them again. here is an example i will post it in one minute
here you go!:
//this is the variable holding the switch
/*I I I I I*/
/*V V V V V*/
var switch1 = {
var choice = prompt("do you choose EXAMPLE or EXAMPLE").toUpperCase()
switch(choice) {
case 'EXAMPLE':
//this will repeat the whole prompt
switch1
break;
default:
//this will repeat it too
switch1
break; }
}
So how would i do this and make java accept this #ajaysinghdav10d?
JavaScript allows you to nest switch statements.
Have a look at this dummy example in which a service returns the location of the customer and his choice of product. Based on the combination of Choice and Location, a function to return the co-ordinates of the nearest store is called; I have used dummy values where ever necessary and alerts to explain the flow of control within the nested switch statements:
var choice = "CHO2"; /* call getChoice() function returning values from {CHO1, CHO2, ...}*/
var location = "LOC1"; /*call getLocality() function returning values from {LOC1, LOC2, ...}*/
switch (location) {
case "LOC1":
switch (choice) {
case "CHO1":
/* redirectToCHO1ofLOC1() is a function returning co-ordinates of the store*/
alert("redirectToCHO1ofLOC1");
break;
case "CHO2":
alert("redirectToCHO2ofLOC1");
break;
default:
alert("redirectToRegret");
break;
}
break;
case "LOC2":
switch (choice) {
case "CHO1":
/* redirectToCHO1ofLOC2() is a function returning co-ordinates of the store*/
alert("redirectToCHO1ofLOC2");
break;
case "CHO2":
alert("redirectToCHO1ofLOC2");
redirectToCHO2ofLOC2();
break;
default:
alert("redirectToRegret");
break;
}
break;
default:
alert("redirectToRegret");
break;
}
Updated answer based on the new context :
You must use recursion for that matter. Put your switch inside a function and call that function from the case statement of your switch, please have a look at this:
function recursiveSwitch() {
var choice = prompt("do you choose EXAMPLE or EXAMPLE").toUpperCase()
switch (choice) {
case 'EXAMPLE':
//this will repeat the whole prompt
recursiveSwitch();
break;
default:
//this will repeat it too
recursiveSwitch();
break;
}
}
Now just call the recursiveSwitch function from where ever you want and an endless loop would start.

Why isn't my variable changing?

I am trying to use the following switch statement in order to change a global variable, but it will only change once.
HTML
<button type="button" value =15>16x16</button>
<button type="button" value =31>32x32</button>
<button type="button" value =63>64x64</button>
JavaScript
var initial_size = 15;
var $cl;
var $size;
$(document).ready(function(){
populate(initial_size);
});
function populate(size){
$('.main-table').empty();
$size = size;
switch($size){
case 15:
$cl = 'box';
break;
case 31:
$cl = 'bigger-box';
console.log("case 31");
break;
case 63:
$cl = 'biggest-box';
console.log("case 63");
break;
default:
break;
}
console.log($cl);
for(var i=0; i < $size; i++){
$tr = $("<tr></tr>");
for(var j=0; j < $size; j++){
$div = $("<div class=" +$cl+"></div>");
$div.css('background-color', 'lightslategrey');
$tr.append($("<td></td>").append($div));
}
$(".main-table").append($tr);
}
run();
};
function run(){
$('.box').hover(function(){
$(this).css('background-color', 'black');
});
$('button').click(function(){
console.log($(this).val());
populate($(this).val());
});
};
So when I run my code, $cl will be set to 'box', but whenever I click on another button and the loop runs again, $cl does not change to any of the other classes. Am I using the switch statement wrong, or am I not parsing the value correctly, or is the problem because I am using global variables? The only reason I am using global variables is because I am not too familiar with how scoping works in javascript yet, so I figured this way might be easier.
Am I using the switch statement wrong, or am I not parsing the value correctly?
Exactly this. The values of your buttons are strings, but your switch statement is operating on numbers. case statements use strict equality which includes the type. So either parse your values to numbers, or use string literals in your cases. Currently, your code will always reach the default case.
The only reason I am using global variables is because I am not too familiar with how scoping works in javascript yet, so I figured this way might be easier.
Quite simple actually: All function declarations, parameter declarations, and var declarations are scoped to the function that contains them. You really should be using local variables here.
Btw, you really should move that run(); invocation from populate into the document-ready callback, next to populate(initial_size);. Currently, you are attaching a new set of event listeners every time you click a button, and all those listeners will fire on each click.

evaluating element class names of jquery array in a switch statement nested in for loop (javascript/jquery)

this is my first post ever on stackoverflow! I am a front-end web developer enthusiast and novice...If I am breaching the stackoverflow etiquette or rules of the road please let me know or give me the smack down..
I am trying to evaluate class names in an array of elements. If the class name contains a certain value then I want to manipulate an attribute for that element.
First, I create an array of elements using jquery stored as a variable:
note that buttons class naming convention is "share_button_[social media service name]"
Next, I create a for loop to iterate through the buttons variable
Within the for loop I have switch statement - the purpose is to evaluate each element in the Buttons array and add an href attribute to the element if it meets a certain criteria
Putting it all together:
var buttons = $('a[class^="share_button"]');
for (i=0; i < buttons.length; i++) {
switch (true) {
case ($(buttons[i]).attr('[class*="twitter"]')):
console.log('twitter!');
break;
case ($(buttons[i]).attr('[class*="linkedin"]')):
console.log('linkedin!');
break;
case ($(buttons[i]).attr('[class*="facebook"]')):
console.log('facebook_like!');
break;
case ($(buttons[i]).attr('[class*="google_plusone"]')):
console.log('google_plusone!');
break;
case ($(buttons[i]).attr('[class*="reddit"]')):
console.log('reddit!');
break;
}
}
This does not seem to be working at all. Here is the codepen, http://cdpn.io/fKoak
Is it a good practice to loop through a jquery array of elements like this?
Should I be using the switch statement in this case and am I using it correctly? (there are more possible cases then I have case statements for and I have no default - I want the cases without a match to "do noting")
In this particular case, what i wrong with the formation of my code that the desired outcome is not happening?
I think it would be better to do something more like this.
var $buttons = $('a[class^="share_button"]');
var $twitterButtons = $('[class*="twitter"]', $buttons);
$twitterButtons.each(function(i, button) {
//Do stuff to the twitter button
});
var $linkedinButtons = $('[class*="linkedin"]', $buttons);
$linkedinButtons.each(function(i, button) {
//Do stuff to the linkedin button
});
var $facebookButtons = $('[class*="facebook"]', $buttons);
$facebookButtons.each(function(i, button) {
//Do stuff to the facebook button
});
var $google_plusoneButtons = $('[class*="google_plusone"]', $buttons);
$google_plusoneButtons.each(function(i, button) {
//Do stuff to the google_plusone button
});
var $redditButtons = $('[class*="reddit"]', $buttons);
$redditButtons.each(function(i, button) {
//Do stuff to the reddit button
});
Adding the second parameter to your selectors gives them a context. So $('[class*="twitter"]', $buttons) looks through $buttons and selects those with a class containing twitter
You can use jQuery's each() method to iterate over the elements, then check the className
$('a[class^="share_button"]').each(function(i, elem) {
if ( elem.className.indexOf('twitter') != -1 ) {
console.log('twitter');
}else if ( elem.className.indexOf('linkedin') != -1 ) {
console.log('linkedin');
}else if (..... etc
});
A better approach would be to keep the switch, but google_plusone kinda screws that up with the underscore, so you'd have to replace that with something else:
$('a[class^="share_button"]').each(function(i, elem) {
switch( elem.className.split('_').pop() ) {
case 'twitter' :
console.log('twitter');
break;
case 'linkedin' :
console.log('linkedin');
break;
case 'googleplusone' :
// you'll have to remove the underscore or just check for "plusone"
}
});
I ultimately decided to drop the for loop and use jquery .each method -http://api.jquery.com/each/ - that was recommended by #adeno above. The two solutions offered by #adeno using .each both work good but I finally chose to go with the jquery .is method https://stackoverflow.com/a/2240085 - http://api.jquery.com/is/ - since we decided to use .each method it is already a "jquery solution" so using .is method to evaluate if the class name of each element contained a certain value was a lot less code - and allowed for more flexibility then the proposed .indexOf and .split/.pop methods by #adeno in imo..
#Tom also gave a workable solution. However, although I didn't mention it specifically in my question, I wanted a solution that would use an iterator to go through the array of selected button elements.
var $buttons = $('a[class^="share_button"]');
$buttons.each(function(i,e){
switch (true) {
case ($(e).is('[class*="twitter"]')):
alert('yea! it\'s a twitter button - now do something');
break;
case ($(e).is('[class*="linkedin"]')):
alert('yea! it\'s a linkedin button - now do something');
break;
case ($(e).is('[class*="facebook"]')):
alert('yea! it\'s a faceboook button - now do something');
break;
case ($(e).is('[class*="google_plusone"]')):
alert('yeah! it\'s a google plus one button - now do something');
break;
case ($(e).is('[class*="reddit"]')):
alert('yea! it\'s a reddit one button - now do something');
break;
}
});

Changing page content in a switch statement using more than 1 variable in the switch parameter. Can that be done?

The situation I have is a drop down list and an image on a html page. I'm using javascript script. I'm using a switch statement. I've constructed my switch and case statements. So far I got an alert box for each case that displays a unique message in the browser when I make a selection in the drop down list. But I want the image on the page to change with each message. I tried using multiple variables in the switch parameter but that disables the alert boxes. Is there a way for me to use a single switch variable that can call the message boxes and the images? Or is there a way to use multiple variables in the switch parameter? I've been researching the internet, even this forum for answers, but haven't found anything that matches my problem. I found some answers using if statements and AJax but that is outside of the scope of my homework and what we've learned so far. So basically my task is to use a switch construct to evaluate the selection and when a match is found, display the appropriate image and the alert box. Any suggestions.
It doesn't sound like you need multiple variables in the switch expression. Rather, you need multiple statements in each branch of your switch. For example:
switch(selectedValue)
{
case 'foo':
alert('foo');
imageElement.src = 'http://foo';
break;
case 'bar':
alert('bar');
imageElement.src = 'http://bar';
break;
}
You can change the source of the image for each case. Switch statements only accept one parameter.
HTML
<img src="image_path" id="myImage" />
JavaScript
var img = document.getElementById( "myImage" );
switch( value ) {
case 0:
alert( "message" );
img.src = "new_path";
break;
case 1:
alert( "message" );
img.src = "new_path";
break;
default: break;
}

Categories

Resources