On-click assigned function with multiple parameters - javascript

I am creating a game which involves numbers. The idea is simple, If i click a number(from 1 to 6) and my code randomly picks one(also from 1 to 6). If my choice(onclick) equals to cpu's choice, the game will be over! If they both are unlikely numbers, my score adds up!
Now the question is, if i click "1" or "2"..(and so on) i need a very new function for all of the numbers.
The code looks like this,
<button id="runs" onclick="i0()">0</button>
<button id="runs" onclick="i1()">1</button>
<button id="runs" onclick="i2()">2</button>
<button id="runs" onclick="i3()">3</button>
<button id="runs" onclick="i4()">4</button>
<button id="runs" onclick="i5()">5</button>
<button id="runs" onclick="i6()">6</button>
I should write each and every function repeatedly which is almost the same! How can i use parameters instead which involves only one function. And how can i add an "if" statement in which the condition should say that i clicked "1".etc
Like,
if(Clicked one//for example) {
document.getElementById("someId").innerHTML = "You pressed one";//:ex
}
can i use,
function click(i0, i1, i2//etc)
if(i0 == true) {
//some code
}
Please remember! I need to use parameters (I am new to JavaScript).

First, you shouldn't be setting up your event handlers with HTML event attributes as that technique is 20+ years old and has many reasons not to use it (one of which is that you'll wind up writing a lot of redundant event handler calls as you are doing now).
Please remember! I need to use parameters
No, you don't (unless this is some sort of school assignment which you didn't state - and if that is the case, get your money back for the course because the instructor shouldn't be teaching you outdated ways of writing code, even for learning purposes). Each button is already displaying the number that corresponds to it. Using a parameter is just more redundancy in the code that makes it more brittle of a solution. You just need a centralized function that runs when any of the buttons gets clicked and then that function can simply compare the random number against the clicked button's content.
Also, you can't have multiple elements with the same id.
Take note of how much cleaner the HTML is when you separate the event handlers out of the HTML and note that this solution works no matter how many buttons you want the game to have. Just make sure that any button that is part of the game has the gameButton class and that the content of the element is the next numeric character that hasn't been used yet.
// Get all buttons into an Array
var buttons = Array.prototype.slice.call(document.querySelectorAll("button.gameButton"));
// Loop over the buttons
buttons.forEach(function(btn){
// Give each button a click event callback function
btn.addEventListener("click", function(){
// Generate a random number from 1 to the number of buttons there are in the game
var num = Math.floor(Math.random() * buttons.length) + 1 ;
var output = "The random was: " + num + ", and the clicked button was: " + this.textContent;
// The prepended + converts the text to a number
if(num === +this.textContent){
alert("You win!\n" + output);
} else {
alert("Keep trying!\n" + output);
}
});
});
/* Just for fun */
.gameButton{
background-color:#800080;
color:#ff0;
font-weight:bold;
font-size:2em;
border-radius:2em;
box-shadow:2px 2px #808080;
outline:none;
}
.gameButton:active{
box-shadow:-2px -2px #808080;
}
<button class="gameButton">1</button>
<button class="gameButton">2</button>
<button class="gameButton">3</button>
<button class="gameButton">4</button>
<button class="gameButton">5</button>
<button class="gameButton">6</button>

You don't need a separate function for each button. You can pass a parameter directly to the function call statement:
<button id="runs" onclick="i(0)">0</button>
<button id="runs" onclick="i(2)">1</button>
...
And then in your JS code:
function i(param) {
...
}
Read more, here: https://www.w3schools.com/js/js_functions.asp

As mentioned, you can not use the same ID on multiple elements.
A good way is to pull the id of the button and pass it to the function, like this:
Have a look at this other question and answers in detail:
How to get ID of button user just clicked?

Related

Javascript simple style.display function only works at random

I have been given an assignment to code my own tic tac toe game. I am fairly new to coding, but absolutely love it. I have for now set up a simple function to just hide the "O", and thus only displaying the X. It's a long way to go, but either way I'd like to start off like this.
However, when I click one of the squares, the "O" only hides at random. Sometimes the first time I click, sometimes after four times. Does anybody know what's wrong?
This is the function I'm working with, and this is how one square is built in html:
function hideO() {
document.getElementById("O" + event.target.id).style.display = "none";
}
<div class="square" >
<button class="1" id="1" onclick="hideO()">
<p class="X1" id="X1">X</p>
<p class="O1" id="O1">O</p>
</button>
</div>
Here's all the code I've got.
The problem here is that event.target returns the element you actually clicked on, so when you think you have clicked on .square, you have actually clicked on the p inside it. One solution here is to use event.currentTarget. It will always return the element to which the click method was attached:
function hideO() {
document.getElementById("O" + event.currentTarget.id).style.display = "none";
}
Also, I have no idea why you are making .grid call hideO. I would remove that.
Edit: this seems to break because event.currentTarget is only valid at the time the event is fired. You can try an alternative solution.
Amend your hideO() function as follows:
function hideO(btn) {
btn.querySelector("#O" + btn.id).style.display = "none";
}
And instead of onclick="hideO()", use onclick="hideO(this)", so that the button that was clicked gets passed in as a parameter. Once you have that button in your function, you can get the "O" element inside it.

How to display and store button values?

very new to coding here, apologies for the basic question. trying to complete the odin project's build-a-calculator challenge (http://www.theodinproject.com/javascript-and-jquery/on-screen-calculator)
and struggling to make numbers appear after they are clicked. Also, how would I store the value in a variable or array to then be used in a calculation later?
Here's the excerpt of my JS:
$(".numbers").on("click", function() {
$+(this).text()
;});
And my HTML (note I'm using jsfiddle, hence the lack of html opening and closing tags etc:
<script src="jquery-1.11.3.min.js"></script>
<div class="numbers">
<button type="button">0</button>
<button type="button">1</button>
<button type="button">2</button>
<button type="button">3</button>
<button type="button">4</button>
<button type="button">5</button>
<button type="button">6</button>
<button type="button">7</button>
<button type="button">8</button>
<button type="button">9</button>
</div>
<div class = "operators">
<button type="button">+</button>
<button type="button">-</button>
<button type="button">*</button>
<button type="button">/</button>
<button type="button">=</button>
<button type="button">clear</button>
</div>
To store the value of the buttons in a variable you could do this.
$('button').on('click', function(){
var i = $(this).text();
console.log(i); // print the value of i in the console
});
Once you have the value you'll need to be able to put the value of each button clicked in order on the "display" of the calculator like so.
HTML
<div class="display"></div>
JavaScript
$('button').on('click', function(){
var i = $(this).text();
var display = $('.display');
display.text( display.text() + i );
});
Hopefully that helps point you in the right direction.
I am not sure how you want to display your numbers. Are you using a TextArea?
For storing values, inside your function do something like
var num=$+(this).text()
Other than that, you need to be more specific.
The following jsfiddle demonstrated how to do what you want.
// array is defined outside the click handler
var clickedArray = [];
$('button').on('click',function() {
// get the button that was clicked
var buttonClicked = $(this).html();
console.log(buttonClicked);
// store it as the last element in the array
clickedArray.push(buttonClicked);
console.log(clickedArray);
// and output it to the screen
$('.js-calc-out').append(buttonClicked);
});
Points to note:
The array is defined outside the click event handler so it can be used without being reset each time a click event is fired. This array will exist until the page is refreshed or it is purposely unset and you can access it as you need it.
The html() function retrieves the contents of any given HTML element, in this case it's the clicked button, which is retrieved using $(this) (any element an event is fired on is retrieved using this which is then converted to a jquery object using the $() function).
The push() function is used to append the latest clicked element to the end of the array mentioned in point 1.
.js-calc-out is an HTML element to which we append() the latest click to, meaning the sequence of clicks are output.
The console.log declarations output some stuff into the inspector which should help you see the process develop.
PS. this is a simplified solution that takes into account your current position on the learning curve; ideally you'd want to use objects to encapsulate data and functionality in javascript and keep out of the global namespace.

Access html elements created by js in other js functions

I am trying to access html elements that I create in one js function in another function. I have this code
EDIT after comments:
here is a jsfiddle
http://jsfiddle.net/8uTxM/
</button>" +"<button value='1' type='button' class='as' id='c2' onclick='cA(this);'>"
in this function
function cA (element){
var x = element.value;
if (x === allQuestions[questionNumber].correctAnswer) {
element.setAttribute.style.backgroundColor = "green";
++score;
}
}
I am trying to make the button green when it is clicked. However, I get the error:
Cannot set property 'backgroundColor' of undefined
I assume this has something to do with timing, but I cannot figure out why. Especially since the element.value bit works (the++score works fine, every right question adds +1 to the score variable)
One problem that I may guess is you are using "getElementsById"
either go for "getElementById" or "getElementsByTagName"
Why don't you create a <div> in your html/php page which would be empty with the answers class, and then change its id/innerHTML ?

JavaScript onclick return

I am new to JavaScript and I'm still figuring things out.
I already searched the web for this but I'm not quite sure what keywords should I use. I am creating some program with a random number using html and JS.
So in my javascript (inside the tag)
I have something like:
var x;
function initRandom() { // I run this function at loading time (i.e: <body onload="initRandom();">)
x = Math.random();
}
function checkGuessedNumber() { // this just checks if the number guessed by the user is == to x and displays "correct" in a div if it is correct otherwise "incorrect"
}
So the main problems I am encountering is that
The html elements gets reset after submit. For example, the text fields becomes blank, the things I displayed in a div becomes blank. It just shows for a short period of time then gets reset
After that, the generated number becomes a different number I think the html page loads once more every time I click submit. And I don't like that to happen.
What I am having confusions on is the return statement on the onClick() attribute and how is it different on without return. See examples below:
CODE1:
<form onsubmit="return checkGuessedNumber();">
<input type="text"> // input for the number
<input type="submit"> // click if already sure of input number above
</form>
CODE2:
<form onsubmit="checkGuessedNumber();"> // notice no return here
<input type="text">
<input type="submit">
</form>
And finally if I'll just gonna put the checkGuessedNumber on <input type="submit" onclick="checkGuessedNumber();"> OR having a return before that.
Here's a live demo (click) of everything in this post.
First, don't use inline js (js functions in your html, like onclick). Read some of these results: Why is inline js bad?
Just for completeness, I'll explain how it works anyway:
This disables the submit nature of the button.
<input type="submit" onclick="return false;">
Now, if you want to use a function, you still need to produce the above result, so:
<input type="submit" onclick="return foo()">
and foo will have to return false, so that return foo() is the same as return false:
function foo() {
//do what you need to do;
return false;
}
I'll update this in a moment explaining the best practice, NOT using inline js.
The best element for a "button" is <button>, so I recommend that.
<button id="my-btn">Click Me!</button>
I gave it an id so that we can easily identify it in javascript. There are plenty of other ways to get element references, but that's another topic. Now, in javascript:
//get the element reference
var myBtn = document.getElementById('my-btn');
//this will make the button call function "foo" when it is clicked.
myBtn.addEventListener('click', foo);
function foo(event) {
//do whatever you want
}
If you assign an event listener to an element that has a default behavior, you can prevent the default behavior like this:
//the "event" object is automatically passed to the event handler
function foo(event) {
event.preventDefault();
//do what you want here
}

Multi-step form

i'm having a problem on how should i implement/build my form. here's the overview.
the first step of the form is to fill up the "Responsibility Center". however, the user can add multiple responsibility center. then the next step would be - each responsibility center added should have one or many "account codes". at the end of the form, before submitting it, all the data should be editable.
the result should be like this:
|**responsibility center**||**account codes**|
| center 1 || account code 1 |
| || account code 2 |
| center 2 || account code 1 |
etc..
i just need some idea on how the form should be built/implemented.
EDIT 1
This is what i've tried
1st step
2nd step
result
EDIT 2
i already know how to add multiple rows (like on the 2nd step) and i can implement that already on the first to the 1st step. so here are my questions:
how can i add account codes per responsibility center?
if what i've tried is not a practical way to implement it, then how should i do it?
Unfortunately, I began writing this answer before you posted the pics of your app. The ideas are still relevant, but I would have tailored my example more to what you are doing. Sorry about that.
I would use jQuery and AJAX to get the job done. jQuery to handle insertion of new elements to the DOM, and for field validation; AJAX to verify that no account codes are duplicated between RCs, or what have you. Personally, I would also use AJAX to handle the form submission instead of using the more traditional <form action= method=> because it gives greater control over the process and doesn't whisk the user off to another page before I am ready. However, it is easiest to describe the <form> example, and you can first build that and then change it over to using AJAX if you want.
The example from here is assuming a blank slate (i.e. I had not seen your sample app before writing this):
First, in your jQuery/javascript, you need a counter to keep track of each RC added. This can be in the <head> tags of your HTML/PHP, or it can be stored in a separate file. If you click on my name and look at other AJAX answers I've given, you'll see many useful examples.
<script type="text/javascript">
$(document).ready(function() {
var ctr = 0;
});
</script>
In your HTML, you need a DIV into which you will append each RC DIV. You also need a link/button/whatever for user to initiate creation of a new RC. This would be a brief form, even just [RC Title] and [Account Code] with a link/button/whatever to create another [Account Code] field and a [Done/Submit] button.
HTML:
<div id="container">
<form action="yourprocessorfile.php" method="POST" id="myform"></form>
</div>
<input type="button" id="mybutt" value="Add New RC" />
JAVASCRIPT/jQuery (again, inside the (document).ready() section above):
$('#mybutt').click(function() {
ctr++;
var str = 'RC TITLE:<br><input id="RC-"'+ctr+' class="RC" type="text"><br>ACCOUNT CODE<br><input id="AC-"'+ctr+' class="AC" type="text"><br>';
$('#myform').append(str);
});
When user presses [Done], use jQuery again to check that each [Account Code] field has been completed.
$('#done').click(function() {
$('.RC').each(function() {
if ($(this).val() == '') {
alert('Please complete all fields');
$(this).focus();
return false;
}
});
$('.AC').each(function() {
if ($(this).val() == '') {
alert('Please complete all fields');
$(this).focus();
return false;
}
});
$('#myform').submit();
});
Edit 2 / Question 1:
You can add new account codes linked to an RC by:
You need to somehow assign a unique data element to the RC, such as an incrementing ID
have a link for adding the new AC
use jQuery to get the ID of the nearest RC element
use .split() to split-off the numerical portion (assign to a var)
use that number when creating your AC
$('.add_AC').click(function() { //Note I used a class, so you can have a link for each RC
var num = $(this).parent().attr('id').split('-')[1];
var str = '';
});
In the above example:
==> Because I used a class, it will fire whenever ANY element with that class is clicked. Of course, when you create the button, you must add that class to the button def, as:
<input type="button" class="add_AC" value="Add Account Code" />
num ==> uses chained jQuery methods to, one-after-another, get the number portion of the RC's id.
$(this) ==> whichever [Add Account Code] button/link/whatever was clicked on.
.parent() ==> This may or may not be correct for your situation. This is the part where we traverse the DOM to find the RC element's ID code, which would look like this: RC-3. You will need to experiment with:
.parent().parent()
.sibling()
.parent().sibling()
.closest()
.prev() or .next()
Play with these selectors, with Dev Tools window opened. It should only take a handful of minutes to find your RC element -- or ask another question and post your HTML.
.attr('id') ==> Obviously, returns the text of the ID, in our case RC-3
.split('-')[1] ==> Creates an array with RC on one side (zero), and 3 on the other (1)
Hopefully this all gives you some idea of where to begin...

Categories

Resources