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>
Related
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
I want to run specific piece of code repeatedly as long as arrow keys are pressed. I have tried to pick up as much things as I can in a week about JavaScript and have written this code (see below), but it isn't working. Right now I am trying to print a something on the page, but in final implementation I would need to run a file repeatedly. Also I would like to know a way to print the results of newly executed function without erasing anything that's already on the screen.
<html>
<head>
<title>
</title>
</head>
<body>
<script>
document.write("Script loaded <br/>");
document.onkeydown=initiate;
function initiate{
$(document).keydown(function(event) {
keyCode=event.keyCode;
event.preventDefault();
});
}
if(keyCode==38){
window.setInterval({a()},100);
function a(){
document.write("Up key</br>");
}
else if(keyCode==39){
window.setInterval({b()},100);
function b(){
document.write("Right key</br>");
}
else if(keyCode==40){
window.setInterval({c()},100);
function c(){
document.write("Down key</br>");
}
else if(keyCode==41){
window.setInterval({d()},100);
function d(){
document.write("Left key</br>");
}
</script>
</body>
</html>
P.S.: Please excuse my bad scripting skills. I tried to grasp everything in a hurry in order to integrate it into a project I am working on.
Please clean up your code a little.you are making things unnecessatily complex
Define all you functions a,b,c,d and then use the following code.If you are using jquery,use appropriate handler.
document.onkeydown = function() {
switch (window.event.keyCode) {
case 37:
window.setInterval(a,100);
document.write("left key</br>");
break;
case 38:
window.setInterval(a,100);
document.write("up key</br>");
break;
case 39:
window.setInterval(c,100);
document.write("right key</br>");
break;
case 40:
window.setInterval(d,100);
document.write("down key</br>");
break;
}
};
Note:
1.It is a better practice to use innerHTML instead of document.write.
2.Use keydown, not keypress for non-printable keys such as arrow keys
Problems in your code
if-else block is not correct.
embedded if-block in the keydown event handler
Define function separately
$(document).keydown is jQuery, not native JavaScript, you don't need it.
Code:
document.write("Script loaded <br/>");
document.onkeydown = initiate;
function initiate() {
keyCode = window.event.keyCode;
event.preventDefault();
if (keyCode == 38) {
window.setInterval({
a()
}, 100);
} else if (keyCode == 39) {
window.setInterval({
b()
}, 100);
} else if (keyCode == 40) {
window.setInterval({
c()
}, 100);
} else if (keyCode == 41) {
window.setInterval({
d()
}, 100);
}
}
function a() {
document.write("Up key</br>");
}
function b() {
document.write("Right key</br>");
}
function c() {
document.write("Down key</br>");
}
function d() {
document.write("Left key</br>");
}
I'm trying to get the value from combobox-items,
so i can give each a different function...
this is the combobox :
<select id="ComboBox" >
<option value="bios">Bioscopen </option>
<option value="dogs">HondenToiletten</option>
<option value="doctors">Huisartsen</option>
</select>
How can i see what is selected with jQuery and give them each another
function?
Thanks in advance!
var a = $("#ComboBox").val();
alert (a);
then depending of received value run corresponding function
switch(a){
case : "bios" dosomething(); break
case : "doctors" dosomething_else(); break
default: break;
}
Something (rustic) like that, see jsFiddle
If you only want it to be launched when a change event happens, you can remove the $(document).ready(....) part
function bios() {
alert("bios is selected");
}
function dogs() {
alert("dogs coming");
}
function getVal(v) {
switch(v) {
case "bios":
bios();
break;
case "dogs":
dogs();
break;
default:
alert('other');
break;
}
}
$('#ComboBox').change(function(){
getVal($(this).val());
});
$(document).ready(function() {
getVal($('#ComboBox').val());
});
I would handle this by binding on the change element of the select element, and then calling another function in the callback. So maybe something like:
$('#ComboBox').change(function() {
var selectedItem = $(this).val();
if (selectedItem === 'bios'){
// Your code here, maybe another function call etc...
} else if (selectedItem === 'dogs'){
// More code
}
// and so on and so on
});
This isn't a super graceful way to handle this, but I hope it helps.
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");
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