Button Switch case - javascript

I can't seem to get this to work in jquery. I am using this code as an alternative to having to define each button, however this does not work :/
http://jsfiddle.net/pufamuf/FV4jW/1/
Also, I was wondering if/how I can use more than one statement for each case. Thank you :)

You need to add a break after each case in your switch statement. Updated JSFiddle here.
From Wikipedia:
break; is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block.
Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
Updated Javascript:
$("input[type='button']").click(function() {
switch(this.id) {
case 'buttonone': $("#content").html("Content changed"); break; //notice BREAK
case 'buttontwo': $("#content").html("Content changed again"); break;
}
});

$("input[type='button']").click(function() {
switch (this.id) {
case 'buttonone':
$("#content").html("Content changed");
break;
case 'buttontwo':
$("#content").html("Content changed again");
break;
}
});

$("input[type='button']").click(function() {
switch(this.id) {
case 'buttonone' :
$("#content").html("Content changed");
break;
case 'buttontwo' :
$("#content").html("Content changed again");
break;
}
});

$("input[type='button']").click(function() {
switch($(this).attr('id')) {
case 'buttonone' : $("#content").html("Content changed"); break;
case 'buttontwo' : $("#content").html("Content changed again"); break;
}
});
You forgot the break after each case, had an extra )} at the end and also you need to use $(this).attr('id') instead of this.id

Related

Call to action are not working inside scrollable sections of fullpage.js

I've embedded fullpage.js in my page and on the sections which have scroll in it, Links, submit buttons and checkboxes doesn't seems to be working in it.
I tried putting an alert on click of a link for testing
$('.project-image').click(function(){
alert('hola')
})
even this simple thing is not working and there is no error on console.
it looks like something is preventing clicks.
Thanks guys I figured it out.
after removing switch case: a.preventDefault(); from handleEvent: function(a) from the file scrolloverflow.js all the links are working now.
I was freaking out before so for others I am attaching the sample code for reference.
handleEvent: function(a) {
switch (a.type) {
case "touchstart":
case "pointerdown":
case "MSPointerDown":
case "mousedown":
this._start(a);
break;
case "touchmove":
case "pointermove":
case "MSPointerMove":
case "mousemove":
this._move(a);
break;
case "touchend":
case "pointerup":
case "MSPointerUp":
case "mouseup":
case "touchcancel":
case "pointercancel":
case "MSPointerCancel":
case "mousecancel":
this._end(a);
break;
case "orientationchange":
case "resize":
this._resize();
break;
case "transitionend":
case "webkitTransitionEnd":
case "oTransitionEnd":
case "MSTransitionEnd":
this._transitionEnd(a);
break;
case "wheel":
case "DOMMouseScroll":
case "mousewheel":
this._wheel(a);
break;
case "keydown":
this._key(a);
break;
case "click":
this.enabled && !a._constructed && (a.preventDefault(), a.stopPropagation())
}
}
Just remove the last case "click"

How to get the user key pressed while inside a loop in native/pure JS?

I have no idea how to perform a "getch()-like" function in Javascript while inside a loop.
Here is my running code and I want to add a user interface based on what he presses:
SNK.moveSnk = function(){
(function myLoop(){
setTimeout(function(){
SNK.ctx.fillRect(SNK.x,SNK.y,10,10);
switch(SNK.mD){
case 1:
SNK.y-=11;
if(SNK.y>=1) myLoop();
break;
case 2:
SNK.y+=11;
if(SNK.y<=496) myLoop();
break;
case 3:
SNK.x-=11;
if(SNK.x>=1) myLoop();
break;
case 4:
SNK.x+=11;
if(SNK.x<=551) myLoop();
break;
}
},100);
})();
}
the SNK.mD should be changed based on the keyboard input.
You can use the onkeypress event, then check for the character introduced and take the required action. Exmample:
document.onkeypress = function(e) {
console.log("Key pressed code: " + String.fromCharCode(e.charCode));
}
Use the window listener 'keypress'.
https://developer.mozilla.org/en/docs/Web/API/event.which

My code is not showing back the elements

I have this jQuery code below:
$("#options").popup(null, Settings.DialogOptions)
.on("onOk", function(){
Settings.SaveSettings( );
Settings.CloseSettings( );
switch(Settings.GetSetting("displayId")){
case "true":
$("#nextId").show();
$("label[for=nextId]").show();
break;
case "false":
$("#nextId").hide();
$("label[for=nextId]").hide();
break;
}
});
I have to cases for testing my code:
displayId = false : the code works properly, it hides my two elements
displayId = true : the code doesn't work, my elemnents aren't shown back.
I don't get any error in console, but I don't know what to do to make my code work.Who can help me?
If you're really dealing with a string, it could be an issue of whitespace, or capitalization:
// ----v -----v
switch($.trim(Settings.GetSetting("displayId")).toLowerCase() === "true"){
case true: // <== No quotes
$("#nextId").show();
$("label[for=nextId]").show();
break;
case false: // <== No quotes
$("#nextId").hide();
$("label[for=nextId]").hide();
break;
}
Of course, if you're dealing with true or false, if/else is the standard construct:
if ($.trim(Settings.GetSetting("displayId")).toLowerCase() === "true"){
$("#nextId").show();
$("label[for=nextId]").show();
}
else {
$("#nextId").hide();
$("label[for=nextId]").hide();
}
Or as you're just showing/hiding based on a flag:
$("#nextId").add("label[for=nextId]").toggle($.trim(Settings.GetSetting("displayId")).toLowerCase() === "true");

how to write an if else statement in javascript

can anyone help me with this if else statement....
Coding
<script>
$("#id_add_select").change(function(){
if($("#id_add_select" == "2")){
handler(1)
} else {
handler(2)
}
});
function handler(situation){
var situation = situation;
switch (situation)
case 1:
display: (".name")
display: (".address")
case 2:
disable: (".age")
disable: (".email")
}
</script>
html coding
<html>
------
<select name="add_select" id="id_add_select">
<option value="1">working</option>
<option value="2">not working</option>
<option value="3">retired</option>
</select>
-------
my situation is if i select 2"not working" then it will display case 1. else will display case 2. basic one but i just can't figure it out. thanks a million.
This is not right:
if($("#id_add_select" == "2")){
You probably want to do something like:
if($(this).val() == 2) {
You can do more optimizations with your code, but this should be in the right direction:
$("#id_add_select").change(function(){
if($(this).val() == 2){
handler(1)
} else {
handler(2)
}
});
Alternative solution
IMO, using a map object with functions is cleaner than using switch statements in your case. So I would probably do something like:
var actions = {
1: function() {
// first choice logic
},
2: function() {
// second choice logic
}
};
$("#id_add_select").change(function() {
actions[this.value]();
});
Demo: http://jsfiddle.net/PurjS/
if($("#id_add_select" == "2")){ => if($("#id_add_select").val() == "2"){
First of all you aren't getting any value:
<script>
$("#id_add_select").change(function(){
if($("#id_add_select").val()==2){
handler(1);
} else {
handler(2);
}
});
</script>
Don't forget to put the break statement after every case in the switch loop.
Figuring out why certain things can't work
$("#id_add_select" == "2")
Apparently, you intended to check whether the selected element's value was 2. However, without needing to know how jQuery works, it's clear that this cannot work.
For this, you simply need to dissect the statement into its essential parts.
We have a function call $() which we perform by passing one argument: "#id_add_select" == "2".
We notice, that the argument to the function is completely independent of the actual call, which is true for all function calls. What this means is, that the result of the comparison will be passed. Because both operands of the comparison are literals, we can evaluate the expression ourselves and replace it by a constant: "#id_add_select" == "2" is obviously not equal, thus the result will be false.
We conclude, that it is the same as writing: $(false). From here, it should be obvious that this code can't check whether some arbitrary element has the value 2.
In addition to the other answer, be aware of
How Switch/Case works
Be aware, that JavaScript's switch/case statement has fall-through behavior.
This means, that once a case clause is executed because it's value matches the input x, it will execute all code below it until it hits a break; statement to exit the switch/case construct.
In the below example, executing printTo5Or8(1) will not have it terminate after console.log(1), instead, it will "fall through" to console.log(2); until the break; statement!
function printTo5Or8(x) {
switch(x){
case 1:
console.log(1);
case 2:
console.log(2);
case 3:
console.log(3);
case 4:
console.log(4);
case 5:
console.log(5);
break;
case 6:
console.log(6);
case 7:
console.log(7);
case 8:
console.log(8);
}
}
printTo5Or8(1); // Prints 1 2 3 4 5
printTo5Or8(3); // Prints 3 4 5
printTo5Or8(6); // Prints 6 7 8
printTo5Or8(7); // Prints 7 8
Invalid Syntax
The switch/case statement requires a block: { statements; } to follow after switch(expression)! You don't have any.
display: (".name")
display: (".address")
You probably meant display(".name");. At the moment, you have labels that do nothing.
Redundant code
function handler(situation){
var situation = situation; // <-- Remove
The formal parameter list (situation) already declares a local variable situation. It is not necessary to declare it.
Conclusion
I suggest you devote some energy to learning JavaScript as a language. Knowing how JavaScript works will help you to reason about your code and rule "impossible" code that couldn't ever work. Without a good grasp on how programming languages or in this case JavaScript works, programming will feel like mixing together some magic incantations that just happen to do sometimes what you want, but go awry more often than not.
Programming is an exact science, not guessing and luck.
i think this code is more clean:
<script>
$("#id_add_select").change(function(){
if( $(this).val() == "2"))
handler(1)
else
handler(2)
});
function handler(situation){
switch (situation){
case 1:
display: (".name");
display: (".address");
break;
case 2:
disable: (".age");
disable: (".email");
break;
}
}
</script>
a piece of optimized love:
$("#id_add_select").change(handler);
var handler = function () {
switch (this.value) {
case 1:
display(".name");
display(".address");
break;
default:
disable(".age");
disable(".email");
break;
}
};
or this way:
$("#id_add_select").change(function () {
switch (this.value) {
case 1:
display(".name");
display(".address");
break;
default:
disable(".age");
disable(".email");
break;
}
});
or this way:
$("#id_add_select").change(function () {
if (this.value === "1") {
display(".name");
display(".address");
} else {
disable(".age");
disable(".email");
}
});
also dont forget that you need a display and a disable method (but i guess you already have made them because your code looks like you have)
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
$("#id_add_select").change(function(){
if($(this).val() == "2")
handler(1)
else
handler(2)
});
});
function handler(situation)
{
switch (situation){
case 1:
alert(situation);
break;
case 2:
alert(situation);
break;
}
}
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<select name="add_select" id="id_add_select">
<option value="1">working</option>
<option value="2">not working</option>
<option value="3">retired</option>
</select>
</body>
</html>

Refresh page after clearing all form fields (jquery)

Is it possible to refresh the page after clearing all the form fields? Is this a separate function or could it be added to my existing script.
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
$(this).removeAttr("style");
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
I do not know whether this will work really.But you can do this way as well in jquery :
$('#PageRefresh').click(function() {
location.reload();
});
this is rather easy and straight forward.

Categories