How can I call a function from different buttons? - javascript

I am trying to put different buttons with same function in switch statement. Every button needs to call same function but with different switch parameter.
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">
SQRT
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left:
100px;">
SIN
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left:
100px;">
COS
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left:
100px;">
ROUND
</button>
And here is JS code,
<script>
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
if(x > 0 && x < 1000){
switch(x){
case 0:
document.getElementById("btnSQRT");
document.write("nesta");
break;
case 1:
document.getElementById("btnSIN");
document.write("nesta");
break;
case 2:
document.getElementById("btnCOS");
document.write("nesta");
break;
case 3:
document.getElementById("btnROUND");
document.write("nesta");
break;
}
}
else{
alert("Thats not a wanted number");
}
}
</script>

Change all of your onclick="myFunction()" to onclick="myFunction(this)" - that will allow you to test for the switch in myFunction - in which case you want to switch on the button ID rather than the prompt value.
function myFunction(el){ // el will be the button that called the function
var x = prompt("Input number between 1 i 999");
if(x > 0 && x < 1000){
switch(el.id){ // switching on the ID of the button which tells us which math to use
case 'btnSQRT':
alert('The square root is ' + Math.sqrt(x));
break;
.....
I am not sure what 'nesta' and document.write was for, so I removed them here.

You are trying to switch between INT numbers, and "prompt" return a STRING. So, It will never get in any switch statement. To solve this, I just added a "parseInt()" in your prompt variable.
I changed "document.write('nesta')" by inner.HTML('nesta'), so, it changes the text in the button. But, to change the text inside the button, you got to set a variable to each button.
HTML:
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">SQRT</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left: 100px;">SIN</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left: 100px;">COS</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left: 100px;">ROUND</button>
JS:
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
var x = parseInt(x);
if(x > 0 && x < 1000) {
switch(x){
case 1:
var nesta = document.getElementById("btnSQRT");
nesta.innerHTML = 'nesta';
break;
case 2:
var nesta =document.getElementById("btnSIN");
nesta.innerHTML = 'nesta';
break;
case 3:
var nesta = document.getElementById("btnCOS");
nesta.innerHTML = 'nesta';
break;
case 4:
var nesta =document.getElementById("btnROUND");
nesta.innerHTML = 'nesta';
break;
}
} else {
alert("Thats not a wanted number");
}
}

Here you have:
One event listener for all buttons.
getting the "value" from the button using the attribute id. An alternative could be to use a data-attribute (like I did with the 2ed button).
A switch statement for handling what to do next.
It is not completely clear for me if the switch statement is the right approach here. Please comment if you have questions.
document.addEventListener('DOMContentLoaded', e => {
let buttons = document.getElementById('buttons');
let output = document.getElementById('output');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
switch (e.target.id) {
case 'btnSQRT':
output.innerHTML = 'You clicked SQRT';
break;
case 'btnSIN':
output.innerHTML = 'You clicked SIN';
break;
case 'btnCOS':
output.innerHTML = 'You clicked COS';
break;
case 'btnROUND':
output.innerHTML = 'You clicked ROUND';
break;
}
}
});
});
div#buttons {
display: flex;
justify-content: space-between;
}
<div id="buttons">
<button id="btnSQRT">SQRT</button>
<button data-func="SIN" id="btnSIN">SIN</button>
<button id="btnCOS">COS</button>
<button id="btnROUND">ROUND</button>
</div>
<div id="output"></div>

Related

Buttons loads index file on click

I have this code:
$(function() {
/*declare a function call hAddCoin with parameter hValue for value and option for option +,x2,clear or max*/
function hAddCoin(hValue, option) {
var bet = document.getElementById('coincredits'); /*get the element*/
var coins = document.getElementById('coins').innerHTML; /*get the inner of id coins*/
var cur = parseInt(bet.value); /*get the coincredit and convert to integer*/
var res = 0; /*declare res variable for result*/
/*we need to check bet is empty or not*/
if (typeof bet.value === "undefined" || bet.value == "") {
cur = 0;
}
/*cek the option, it's will be +, X2 or max and default to 0*/
switch (option) {
case 1:
{
res = cur + hValue;
}
break;
case 2:
{
res = cur * option;
}
break;
case 3:
{
res = parseInt(coins);
}
break;
default:
{
res = 0;
}
break;
}
bet.value = res; /*set value coin creadit to result*/
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="coincredits" id="coincredits" class="form-control" required="" parsley-type="text" placeholder="Minimum 10 coins" data-parsley-id="40" style="text-align:center; color: ;">
<div class="content" style="text-align:center;">
<button id="clear" class="box-btn" onclick="hAddCoin(0,0)">Clear</button>
<button id="add10" class="box-btn" onclick="hAddCoin(10,1,)">+10</button>
<button id="add100" class="box-btn" onclick="hAddCoin(100,1)">+100</button>
<button id="add1000" class="box-btn" onclick="hAddCoin(1000,1)">+1000</button>
<button id="double" class="box-btn" onclick="hAddCoin(0,2)">x2</button>
<button id="max" class="box-btn" onclick="hAddCoin(0,3)">Max</button>
</div>
It adds (or should add) value to the input field, but it just sends me to mywebsite.com/index.php
I have tried defrient scripts but this is happening every time. It gives me no errors and logs nothing in the console.
I know it might be a piece of cake but i just can't figure it out.
<button> elements are implicitly type="submit" which means they submit the form they reside in. If your <form> doesn't have an action attribute it will use the current page as target URL, which reloads the page.
You need to either explicitly set type="button" on each button or add an onsubmit event handler on the form that invokes event.preventDefault()

Javascript ignoring variable in switch statement

Im trying to make a case statement but my variable for my first switch statement just goes to my default statement when i really have a string in my variable for the type of edge such as: "round", "square", "butt". I tested it with alert(tipoextremo) and it does contain the value "round", "square", or "butt".
For the second switch statement, i am trying to get my button names into the switch statement when i click a button in html and do that function inside the case, but when using alert("hi") it does not even go into the default statement meaning that it is being completely ignored in my javascript.
Botones
Borrar
Varias Lineas
Arco
Cuadratica
Berzier
Zig Zag
Espiral
<section id="parametros">
<form action="" method="post" name="parametro">
Color: <input type="text" name="btncolor" id="color" value="red"><br/>
Ancho: <input type="text" name="btnancho" id="ancho" value="10"><br/>
Tipo Extremo: <br/>
Round <input type="radio" name="btntipoextremo" value="round" id="tipoextremo" checked="checked"><br/>
Square <input type="radio" name="btntipoextremo" value="square" id="tipoextremo"><br/>
Butt <input type="radio" name="btntipoextremo" value="butt" id="tipoextremo"><br/>
<button name="btnOK" type="button" value="OK" onclick="parametros()">OK</button>
</form>
</section>
This is my javascript part.
function parametros() {
//var nombre = document.parametro.btncolor.value;
//alert(nombre);
contexto.beginPath();
color = document.getElementById("color").value;
ancho = document.getElementById("ancho").value;
alert(color);
alert(ancho);
var boton_te = document.forms[0];
var i;
for (i = 0; i < boton_te.length; i++) {
if (boton_te[i].checked) {
tipoextremo = tipoextremo + boton_te[i].value + " ";
}
}
document.getElementById("tipoextremo").value = tipoextremo;
alert(tipoextremo);
$("button[type='button']").click(function()
{
switch(this.name){
case 'btnarco':
fun_arco(color, ancho, tipoextremo);
alert("Hi");
break;
case 'btncuad':
fun_cuad(color, ancho, tipoextremo);
break;
case 'btnbezier':
fun_bezier(color, ancho, tipoextremo);
break;
case 'btnzigzag':
fun_zigzag(color, ancho, tipoextremo);
break;
case 'btnespiral':
fun_espiral(color, ancho, tipoextremo);
break;
default:
alert("hi");
break;
}
});
}

Using an external file on a button in html

<button onclick = "button javascript.js">
What do you drive? </button>
I want the button to run my switch() in the button javascript.js file
var car = prompt('What car?');
switch(car) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
You can put the code in a function inside the javascript. Include the file in script tags and on click of the button, call that function. That will trigger the JS code only on click of the button.
Put this in the HTML,
<script src='button javascript.js'></script>
//Intermediate HTML code
<button onclick = "myButtonFun()">
What do you drive? </button>
And in the Javascript you can put in your code in the function myButtonFun()
function myButtonFun()
{
var car = prompt('What car?');
switch(car) {
case 'ferrari': document.write("you are probs a baller then");
break;
case "porsche": document.write("do you ball hard?");
break;
case "dodge": document.write("american cannot corner");
break;
default: document.write("your car better be a subaru");
}
}
Make your code into a function and, on the button, use
type="button"
and
onclick="yourFunction()"
You need to wrap your script into function and invoke it on button click:
<button onclick = "askForCar();">What do you drive?</button>
var askForCar = function() {
//you script here
};
var askCar = function() {
switch (prompt('What car?')) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
};
<button onclick="askCar();">What do you drive?</button>

Comparing attribute value with a random number (JavaScript/jQuery)

I have a problem with comparing an attribute value and a random number (created in a separated function).
In my html I have several divs within a surrounding div.
Each div within the surrounding element has an attribute, called 'value', the first one contains the value: 1, the second one: 2, ...
Like this:
<div id="Stage_placeholder_rectangles">
<div id="Stage_placeholder_rectangles_red" value=0 width=25 height=25/>
<div id="Stage_placeholder_rectangles_pink" value=1 width=25 height=25/>
<div id="Stage_placeholder_rectangles_orange" value=2 width=25 height=25/>
...
</div>
Now I want to compare the attribute 'value' with a random number, which was made to show random random colors:
The function is lik this:
function randomNumber(){
random = Math.floor(Math.random() * 9);
return random;
}
function randomColors(){
while(pastRandom == newRandom){
newRandom = randomNumber();
}
pastRandom = newRandom;
switch(newRandom){
case 0:
stageRef.getSymbol("placeholder_colors").stop("red");
break;
case 1:
stageRef.getSymbol("placeholder_colors").stop("black");
break;
case 2:
stageRef.getSymbol("placeholder_colors").stop("yellow");
break;
case 3:
stageRef.getSymbol("placeholder_colors").stop("green");
break;
case 4:
stageRef.getSymbol("placeholder_colors").stop("orange");
break;
case 5:
stageRef.getSymbol("placeholder_colors").stop("pink");
break;
case 6:
stageRef.getSymbol("placeholder_colors").stop("blue");
break;
case 7:
stageRef.getSymbol("placeholder_colors").stop("gray");
break;
case 8:
stageRef.getSymbol("placeholder_colors").stop("purple");
break;
}
checkColor(newRandom);
}
In my function checkColor, I want to compare the random number with the value that is stored in the attribute value of 'placeholder_rectagles_orange', 'placeholder_rectagles_red', ...
This is my function:
function checkColor(rnd){
if(gameStarted){
$("#Stage_placeholder_rectangles").click(function(e){
if($("#"+e.target.id).attr("value") == rnd){
console.log("right");
}
else if($("#"+e.target.id).attr("value") != rnd){
console.log("false");
gameOver = true;
}
});
}
}
My problem is, that when I the right element (the one with the same value in his attribute 'value' as the random number, I get in my console:
"right" and multiple times "false", even when my attributes value and random number are the same.
I think part of your problem is the usage of rnd, which is not defined earlier, but we don't have all of your code.
Here it is working:
<div>Please click the colour: <span id="name"></span></div>
<p/>
<div id="Stage_placeholder_rectangles">
<div id="Stage_placeholder_rectangles_red" class="square red" value=0 width="25" height="25"></div>
<div id="Stage_placeholder_rectangles_pink" class="square pink" value=1 width="25" height="25"></div>
<div id="Stage_placeholder_rectangles_orange" class="square orange" value=2 width=25 height="25"></div>
</div>
<p/>
<div id="result"></div>
And the JS:
var colors = ["red","pink","orange"],
gameStarted = true, newRandom, pastRandom;
function randomNumber(){
random = Math.floor(Math.random() * 3);
return random;
}
var giveOption = function() {
while(pastRandom == newRandom){
newRandom = randomNumber();
}
pastRandom = newRandom;
$("#name").html(colors[newRandom]);
};
$("#Stage_placeholder_rectangles").click(function(e){
var val = $(e.target).attr("value"),
resultDiv = $("#result");
if(val == newRandom){
resultDiv.html("right!");
giveOption();
} else {
resultDiv.html("Wrong! Sorry. Game over");
gameOver = true;
}
});
giveOption();
There also is a lot of stuff that could be simplified using arrays and jquery, but I left it for now.
Fully functional jsfiddle at http://jsfiddle.net/obqmwLet/1/

how to reset form in firefox browser by javascript

I want to reset form in firefox browser. When I use previous function in back button, the page is not reset for hidden field. It has previous stage. So, How do I?
<Html>
<Head>
<Title>My Testing for javascript</Title>
<Script type="text/javascript">
function hidetext(){
window.alert('Start save to hidden');
document.getElementById('hid').value = document.getElementById('puttextbox').value;
window.alert('Complete save to hidden');
document.getElementById('puttextbox').value='';
}
function displaytext(){
window.alert('Start display from hidden');
document.getElementById('displaytextbox').value = document.getElementById('hid').value;
window.alert('Complete display from hidden');
}
function resetform(){
document.getElementById('form1').reset();
window.alert('reset is completing.....');
}
</Script>
</Head>
<Body>
<form id="form1">
<div>
Type your hidden text <input type="text" id="puttextbox"/>
<br/>
Display your hidden text <input type="text" id="displaytextbox"/>
<br/>
<input type="hidden" id="hid"/>
<button type="button" id="putbutton" onclick="hidetext();">Put the textbox</button>
<button type="button" id="displaybutton" onclick="displaytext();">Display hidden text</button>
<button type="button" id="resetbutton" onclick="resetform();">Reset</button>
</div>
</form>
</Body>
</Html>
Why not this:
<input type="reset" value="Reset">
? It's HTML-native. Or try this instead:
window.onload = function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
};
It clears each input element in the page.
function clearForm(oForm) {
var elements = oForm.elements;
oForm.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
That should do the job.
The most simple version is:
document.form1.reset();
However, this resets all input fields to their default value, i.e. the one sent along with the HTML. If you want all fields cleared, you'd need to loop through them all.

Categories