Why isn't my Javascript Switch Case working? - javascript

When using the JSfiddle interpreter, the button and input field appear in the 'result' box, however there doesn't seem to be any response to the script. I tried other interpreters, such as that of the W3School, and while it does give me an indication that the function is in fact being called, the result seems to only be the default case, and even that only appears for a fraction of a second before the entire field along with the button and input disappear (Worth noting the text I input does not appear in the paragraph, and 'fruitT' seems to be ignored -- so most likely there is an issue with the passing of info between the input field, the button and the function.)
The logic seems pretty straightforward to me and I've looked at other examples -- however I am new to JS so I've potentially overlooked some syntax. Hoping somebody could give me a push in the right direction. Thanks!
<!DOCTYPE html>
<html>
<body>
<form action="#">
<input id="fruit">
<button onclick="myFunc('fruit')">Enter</button>
</form>
<p id="here"></p>
<script>
function myFunc(fruitT){
switch (fruitT){
case "Oranges":
document.getElementById("here").innerHTML = ("Oranges are $0.59 a pound.");
break;
case "Apples":
document.getElementById("here").innerHTML = ("Apples are $0.32 a pound.<br>");
break;
default:
document.getElementById("here").innerHTML = ("Sorry, we are out of " + fruitT + ".<br>");
}
}
</script>
</body>
</html>

A button inside a form submits the form, as it's default type is submit, reloading the page.
You probably also want to pass the inputs value to the function, not just the string 'fruit'
change this line
<button onclick="myFunc('fruit')">Enter</button>
to
<button type="button" onclick="myFunc(document.getElementById('fruit').value)">Enter</button>
FIDDLE

<button onclick="myFunc('fruit')">Enter</button>
Passes the string "fruit" to your function, which would then hit default.
<button onclick="myFunc(fruit)">Enter</button>
Would run the function with the variable fruit, if it exists.

Related

How to switch inputted text between 2 colored boxes in html

So far I only have the code that is able to make 2 boxes, made the 4 buttons, but only 1 button actually does something, and that is the start button where a there is a popup that asks for a name, and after you input that name, it will appear in the first box.
<html>
<head>
<script>
function myTask1() {
var sentence = prompt("Please enter a name");
var arrSentence = sentence.split(" ");
if (arrSentence != null) {
document.getElementById("answer1").innerHTML = arrSentence.sort(); //so we can use Array.sort() function
}
console.log(sentence);
return sentence;
}
function myFunction() {
var x = document.getElementById()
}
</script>
<style> </style>
</head>
<body>
<p><button type="button" onclick="myTask1()">Click me!</button></p>
<button type="button" onclick="ClearFields();">Clear</button>
<button type="button" onclick="myFunction()"> --> </button>
<button type="button" onclick="myTask4()"><-- </button>
<div clas="box" style="background-color:red; height:200px; margin:20px auto;">
<center>
<p id="answer1"></p>
<center>
</div>
<div class="box1" style="background-color:grey; height:200px; margin:20px auto;"> </div>
</body>
</html>
I've made some demo code for you. I assume that you're a beginner because the question is basic. This is not a problem though, starting something new is great. You can find the answer on the internet and the best programmers are often people who are good with Google. But I hope by showing you the solution anyway you get a feeling for structure. Try to understand every line. Try write it from scratch afterwards anyway. It's a great exercise.
Code: https://github.com/Bunpasi/stackoverflow-answers/blob/master/js-listbox-selector/index.html
Some things to notice:
- I've put the script in the footer so it doesn't interfere with the loading time of the page.
- I've put all code in an anonymous function to avoid global functions.
- I changed clas to class.
- I've used event listeners instead of even attributes.
- I didn't duplicate the logic for both boxes but used one function which I can use on both.
After your understand the code, there are some things you can improve on this code.
- Make sure the selection doesn't go away after the update. You can store this in the data as well. Right now the data is an array of ID's, but you can turn it into an array of objects containing even more important data, like whether it's selected.
- Move the style from the elements to the header.
Don't be discouraged by down votes.
Good luck!
Update
If you want to move all names all the time. This is what you need to do.
This line looks for all selected elements:
var selectedElements = boxes[fromId].querySelectorAll('.list_item.selected');
Remove the selected .selector:
var selectedElements = boxes[fromId].querySelectorAll('.list_item');

vbscript - displaying a message box when an OnClick event fires

I feel a bit silly asking this question, since most of the questions people ask on here are way beyond my level as a programmer, but at least I know I'm in good hands as far as asking goes. I used to know how to make simple vbscript and javascript programs, but I'm a bit rusty. I'm trying to refresh myself, and despite repeated google/other searches, can't recall how to make it so that when a button is clicked, a msgbox appears. Also, I'd like to know how to modify the .value attribute of a textbox. I'm attempting this in vbscript for now, but I'll try javascript if anyone knows a way to do it in that instead. My ultimate goal is a text based type game where you can click buttons labeled, "north,south,west,east", and make it like an rpg. The textbox would display the current room description.
Here's the code I have so far, which isn't displaying the msgbox.
<html>
<title>Explor-o-Rama!</title>
<body>
<form name = frmMain>
<textarea name = "txtDisp" rows = "10" cols = "50"></textarea><br>
<input type = "button" name = cmdTest value = "test">
</form>
<script language = "vbscript">
sub cmdTest_OnClick
msgbox "test"
end sub
<script>
</body>
</html>
You have:
msgbox "test"
The correct command is:
MsgBox("test")
OR
X=MsgBox("test")
This SHOULD DO IT.
also, <html><body><script language=vbscript>msgbox "" </script></body></html> not works.
but this code works OK:
<html><body><script>alert('Test');</script></body></html>
<html>
<body>
<script>
function test()
{
alert('Test');
}
</script>
<input type = 'button'; onclick='test()'>
</body>
</html>
Probably, it's a IE internal bug.

Can't change button text in HTML and JavaScript

I'm trying to change the text of a button using this code, but I'm not getting any reaction. This should be good, looking at everything I've read through - but it doesn't change the text. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<script>
function changeText() {
document.getElementById('myButton').value = "New value";
}
</script>
</head>
<body>
<button id="myButton" onclick="changeText()">Change my text!</button>
</body>
</html>
You need to set the 'innerHTML' property instead:
function changeText() {
document.getElementById('myButton').innerHTML= "New value";
}
You can specify a value on the button but it's not used very often. In your case you want to the text of the button to change. So innnerHTML is your friend. See this page for more details.
Also note that you could use 'innerText' in IE as well but it is not supported in Firefox (and probably not in some other as well).
'textContent' can also be an option but that one is not supported in older browsers (before 2011). So innerHTML is the safest option.
Buttons can have a value but what is displayed is the HTML inside of the button, which is what you want to change. Better use innerHTML:
function changeText() {
document.getElementById('myButton').innerHTML = "New value";
}
What the other answers said, plus this: buttons generated by the <input> element have a value! That may be where the confusion is coming from:
<input type="button" value="Button Text" id="button42"></input>
What you have is a:
<button>Button Text</button>
element, which is something else; hence innerHTML, not value.

javascript split text into list of words and then dynamically added to div, form tag messing it up

I was testing this code out in an asp.net webform as I am looking to split a text into a list or words in javascript and have each added to its own div.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_split
However in an asp.net webform, the sample code alone produces strange behavior, and the result appears and disappears. Simply adding the form tags to the online sample reproduces the behavior.
<form id="form1" runat="server">
</form>
Is there a workaround for this or alternative ideas to do this in javascript?
Thanks
The behavior you are experiencing is happening because the button is triggering a postback to the server. This essentially reloads the page which is why it appears as though the text is appearing then disappearing right away.
You can fix this by adding in a return false; after onclick="myfunction()" like this:
<form id="form1" runat="server">
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction();return false;">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "How are you doing today?";
var res = str.split(" ");
document.getElementById("demo").innerHTML = res;
}
</script>
</form>
However, I do not recommend using the onclick attribute to call a JavaScript function as there are better ways to do this. For the purpose of your example, I provided the simplest solution to the problem, but I want to make you aware that there are better ways to handle this.
As an extension to Howard Renollet's explanation for the form behavior:
A <button> element has different types. W3Schools mentions that "different browsers may use different default types for the element."
When in a form, the submit and reset types will actually do things to the form! In order to put a button into a form without it submitting the form, set the type to button:
<form>
<button type="button">Yay, I won't submit this form!</button>
</form>

Making an HTML game-ish thing

So I'm using Notepad++ with HTML and javascript to try and make a little clicker game (Similar to cookie clicker if you've ever played it) and I'm just using it to experiment with stuff. I have a uneditable text field and a button that when clicked adds "1" to the value of the textfield. I've been trying to create another button that simply checks for a value greater or equal to five in the text field, then subtract five if it's true. (The ultimate goal is to have three buttons -- One that when clicked checks for a value greater than five, then subtracts five, which makes another button that wasn't clickable become clickable, which will add 10 to the value when clicked kind of like an upgrade.)
I've got the button to add +1 to the value, and I've been trying to get the upgrade one to enable a disabled button. But for some reason the button won't work..
<!DOCTYPE html>
<html>
<head>
<title>Button Clicker</title>
<script language="Javascript">
function handleButtonClick() {
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
// Add one
currentValue = currentValue + 1;
// Put it back with the new +1'd value
textField.value = currentValue;
}
function handlebuttonclick() {
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
// Minus one
currentValue = currentValue - 1;
// Put it back with the new -1'd value
textField.value = currentValue;
}
</script>
</head>
<body>
<script language="Javascript" type="text/javascript">
function enable(){
if (document.form="upgrade".clicked==''){
document.agreement_form.clicker.disabled=true
}else{
document.agreement_form.clicker.disabled=false
}
}
</script>
<button type="button" form="upgrade" onclick="enable()" onclick="handlebuttonclick"/>Upgrade</button>
<br>
<button type="button" onClick="handleButtonClick()"/>Press here</button>
<input type="button" value="Clicker" disabled name="clicker">
<input type="text" value="0" id="textField" readonly/>
</body>
</html>
Here's the bug:
<button type="button" form="upgrade" onclick="enable()" onclick="handlebuttonclick"/>Upgrade</button>
^ ^
| |
\ /
\ /
\ /
\ /
you can't have two onclick handlers
The solution is to simply call both functions in the onclick handler:
onclick="enable();handlebuttonclick()"
Or even call enable from inside handlebuttonclick:
function handlebuttonclick() {
// ..... bunch of code
enable();
}
BTW, some advice:
Try not to confuse yourself by declaring variables and functions with similar names (handlebuttonclick vs handleButtonClick). Just because it works doesn't mean it's "correct". The primary function of source code is to document your intentions. Making the code execute on a computer is actually a secondary function. Give your functions meaningful names:
<button id='increment' onclick='handle_increment()'> + </button>
<button id='decrement' onclick='handle_decrement();enable()'> - </button>
Secondly, and this is minor but since it means less typing and cleaner code it's good to follow: language="javascript" is deprecated and I believe is invalid for HTML5 (which is your DOCTYPE) and type="text/javascript" is unnecessary for HTML5. So just write
<script>
// javascript code...
</script>
Thirdly, self-closing tags like <input ... /> is xHTML and is invalid HTML5 (though browsers will tolerate it, potentially triggering quirks mode (quirks mode is a mode where the browser tries to emulate previous bugs)). Also, you've incorrectly self-closed the <button> tag. The /> at the end of the tag has the same meaning as closing the tag with a </...> tag. So:
<button />
means the same as
<button></button>
Therefore, <button /></button> is invalid.
But that's moot anyway since this is html5 and not xhtml - don't use the />.
There are lots of other things that can be improved such as assigning onclick handler in javascript rather than HTML etc. but they're not strictly "wrong", they're more a matter of style.

Categories