Making an HTML game-ish thing - javascript

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.

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');

JavaScript Help, assign user input values to an array then to an UL

I am a student and this is a homework assignment for my JavaScript class, I have to make the following code work, it should take five places entered from the user and assign them to an array. Then display them in the list on the page. When I started it was not functional. It currently will only take 4 entries and displays only the first 3 on the list. It should take 5 entries and display 5 entries. I have tried to change the if statement that iterates the counter but it still only takes 4 places. I suspect something is out of order, or not numbered correctly. Any help would be greatly appreciated!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hands-on Project 4-3</title>
<link rel="stylesheet" href="styles.css" />
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<header>
<h1>
Hands-on Project 4-3
</h1>
</header>
<article>
<div id="results">
<p id="resultsExpl"></p>
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
</div>
<form>
<fieldset>
<label for="placeBox" id="placeLabel">
Type the name of a place, then click Submit:
</label>
<input type="text" id="placeBox" />
</fieldset>
<fieldset>
<button type="button" id="button" onclick="processInput()">Submit</button>
</fieldset>
</form>
</article>
<script>
var places = []; // new array to store entered places
var i = 1; // counter variable to track array indexes
// function to add input to array and then generate list after 5th submission
function processInput() {
places[i] = document.getElementById("placeBox").value; // add entered value to array
document.getElementById("placeBox").value = "" // clear text box
if (i < 6) { // iterate counter variable
++i;
}
else { // add entered value to array and write results to document
document.getElementById("resultsExpl").innerHTML = "You entered the following places:";
var listItem = "";
for (j = 1; j < 6; j++) { // write each array element to its corresponding list item
listItem = "item" + j;
document.getElementById(listItem).innerHTML = places[j];
}
}
// add backward compatible event listener to Submit button
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
}
</script>
</body>
</html>
There are several issues I see. The biggest one which is probably tripping you up is the fact that processInput() is running twice every time you click the submit button.
First you assign an event handler inline the HTML itself:
<button type="button" id="button" onclick="processInput()">Submit</button>
onclick="processInput()" assigns that click handler when it parses the HTML. So later on when you do this:
// add backward compatible event listener to Submit button
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
}
You're actually adding another duplicate event handler to the button's onclick, causing processInput() to run twice with every click. That causes the array to be filled with some unexpected values.
Another issue is the fact that the above block of code (adding the event listener in JavaScript) is inside of processInput() itself. So this is what happens:
HTML adds event listener to the onclick.
First time the button is clicked, processInput() runs once. processInput() adds a duplicate event listener to the onclick.
Subsequent button clicks fire processInput() twice; once from the HTML and once from the JavaScript.
In conclusion, pick one or the other. Either add the event listener inline in HTML or do it in JavaScript, not both. If you do it in JS, certainly make sure that the code that adds the event listener isn't inside of the function it's adding. Put it in the global context.
There are a couple of other small problems I see but you should be able to figure them out once you fix the event listener issues. A word of advice: when debugging your code it's helpful to add console.log() in certain places so that you can see the state of your variables and track down what is going wrong where.

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.

HTML input into Javascript

I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button
Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.
I think you mean:
var r = document.getElementById("radius").value;
getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);
Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;
You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.
Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.

JavaScript doesn't work in Mozilla Firefox

I wrote the following code:
<form name=f>
<input type=button value="Button1" onclick=b1click()>
<input type=button value="Buttone2" onclick=b2click()>
<script language=javascript>
function b1click()
{
f.action="Login.jsp";
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</form>
This works code properly in Internet Explorer but the action does not work in Mozilla Firefox 3.6.2. How to solve this problem? Please any one help me.
I know this will sound snide, but the truth of the matter is: it's not 1995 anymore.
That code would have worked great a decade ago, but standards and specifications have changed significantly since then.
Lets start from the top:
<form name=f>
All html attribute values should be enclosed in quotes. For consistency sake, use double quotes: <form name="f"> is much better.
<input type="button" value="Button1" onclick="b1click()">
Avoid inline-script events. If the functionality ever changes, or you want to remove a function, you'll have to go through every page and adjust the function. A better way is to give the button an ID, and add the onclick event via scripts:
HTML:
<input type="button" value="Button1" id="button1">
JS:
document.getElementById('button1').onclick = b1click;
Now the script's turn:
<script language=javascript>
You should use the type attribute with a valid MIME type. Additionally, whenever possible, move your scripts to an external script file. When that's not possible, make sure to either XML encode your script, or encase it in CDATA tags:
<script type="text/javascript" src="path/to/script.js"></script>
OR
<script type="text/javascript">
/* <![CDATA[ */
... some code ...
/* ]]> */
</script>
Finally the real issue with your script.
The f property you're referencing is a member of the document, and not the window. I believe IE will put the reference on both, but it's just not safe to rely on either behavior.
Give the form an ID: <form id="f">, and get the element from the b[12]click functions
function b1click()
{
var f = document.getElementById('f');
f.action = 'Login.jsp';
f.submit();
}
First off, change that name="foo" to id="foo". Names are mostly used within the form itself.
Now, try to reference your form using document.formID, not just formID. formID is a variable, which is undefined, but document.formID is the actual form element:
function b1click()
{
document.f.action="Login.jsp";
document.f.submit();
}
function b2click()
{
document.f.action="Logout.jsp";
document.f.submit();
}
Give form an id and refer to it using:
var form = document.getElementById('formId');
You should quote the input attributes, or any attributes for that matter. And your script does not belong AFTER the form, e.g. in body, but rather in the HEAD element.
This works in IE, Firefox and Chrome.
<html>
<head>
<script language="javascript">
function b1click()
{
f.action="Login.jsp"; // better is document.f., but f. appears to work as well
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</head>
<body>
<form name="f">
<input type="button" value="Button1" onclick="b1click()">
<input type="button" value="Buttone2" onclick="b2click()">
</form>
</body>
</html>
There are a couple ways to reference your form.
If you define your form as <form name="Login" id="LoginFrom"></form>,
Method 1
If your form is the only one in the page, you can use:
document.forms[0].action = 'Login.jsp';
Method 2
If your form is not the only one form in the page, you can use the form name to reference the form, such as
document.Login.action = 'Login.asp';
Method 3
The form can also be referenced with DOM function getElementByID.
document.getElementByID('LoginForm').action = 'Login.asp'

Categories