Multiple JavaScript Buttons (Variables) - javascript

I'm just beginning JavaScript, and I was wondering how to make different buttons do different things. So far, I can make one button do one thing, but how do I make a second button do a different thing? Here's the coding:
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Your Name");
if (name!=null && name!="")
{
alert("Thanks for clicking " + name + "!");
window.top.location.replace("http://www.google.com");
}
}
</script>
</head>
<body>
<ul>
<li>
<input type="button" onclick="show_prompt()" value="Button One" />
</ul>
</body>
</html>

I will guess you meant like doing different things with different buttons but from the same function:
JavaScript:
function myFunction(str) {
if(str.length > 3){
alert("big");
}else{
alert("small");
}
}
HTML:
<input type="button" onclick="myFunction('test');" value="Button 1" />
<input type="button" onclick="myFunction('hi');" value="Button 2" />
In case my assumption is wrong, just create different functions and replace the button's onclick with their respective function

Define another function and bind the second button to it!
function alert_hi() {
alert("Hi!");
}
<input type="button" onclick="alert_hi()" value="Button Two" />
If that catches your interest I highly recommend Eloquent Javascript.

Making the second button do something is basically identical to making the first do something. It'd just be two functions and two buttons. I think this is what you're asking about.
<html>
<head>
<script type="text/javascript">
function doSomething()
{
// Do something when button one is clicked
}
function doSomethingElse()
{
// Do something else when button two is clicked
}
</script>
</head>
<body>
<input type="button" onclick="doSomething()" value="Button One" />
<input type="button" onclick="doSomethingElse()" value="Button Two" />
</body>
</html>

If you're serious about learning.. you can read up about Event Registration models.
in the case of your example.
js
var btn1 = document.getElementById('btn1'),
btn2 = document.getElementById('btn2');
btn1.addEventListener('click', show_me, false); // i am not IE friendly
btn2.addEventListener('click', show_me, false); // you can replace show_me with any function you would like.
function show_me() {
alert(this.value + ' was clicked'); // this references the element which the click event was invoked on.
}
html
<input type="button" id="btn1" value="Button One" />
<input type="button" id="btn2" value="Button Two" />

Related

jQuery document ready functions not working

I'm working on a form with 5 divs and to keep the form as clean and tidy as possible, I kept 4 of them hidden with "display: none".
When the button (ex. Add Client) is clicked, I want the next div (up to 4 more) to be displayed with a js, and when the other button (ex. Remove Client) is clicked, I want the last displayed div to be hidden again.
JS:
<script>
$(document).ready(function addClient() {/*mycode*/});
$(document).ready(function removeClient() {/*mycode*/});
</script>
HTML:
<input id="kkBtnNewClient" type="button" value="New Client" class="kkButton" onclick="addClient()"/>
<input id="kkBtnRemoveClient" type="button" value="Remove Client" class="kkButton" onclick="removeClient()"/>
I tried to put a simple alert in the /mycode/ part, but I don't even get to that part.
The value you pass to ready() is called when the ready event fires.
It does not create a global variable from which to call the function.
Use a function declaration to do that. Better yet, bind the event handler with JavaScript and don't use onclick attributes at all.
$("#kkBtnNewClient").on("click", function addClient() {
alert("add client");
});
$("#kkBtnRemoveClient").on("click", function removeClient() {
alert("remove client");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="kkBtnNewClient" type="button" value="New Client" class="kkButton" />
<input id="kkBtnRemoveClient" type="button" value="Remove Client" class="kkButton" />
You may try like as below:
$(".group_1").hide();
$(".group_2").hide();
$(document).on('click','#kkBtnNewClient', function(){
console.log("kkBtnNewClient clicked");
$(".group_1").show();
$(".group_2").hide();
});
$(document).on('click','#kkBtnRemoveClient', function(){
$(".group_2").show();
$(".group_1").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="group_1">
div 1
</div>
<div class="group_1">
div 2
</div>
<div class="group_1">
div 3
</div>
<div class="group_1">
div 4
</div>
<div class="group_2">
div 5
</div>
<input id="kkBtnNewClient" type="button" value="New Client" class="kkButton" />
<input id="kkBtnRemoveClient" type="button" value="Remove Client" class="kkButton" />

Changing button created with <button> text with JavaScript

My code looks like this
in .html
<button type="button" onclick="toggle()" id="toggleButton">more ⇓</button>
.js
function toggle(){
document.getElementById("toggleButton").innnerHTML="less ⇑";}
The button appears in my page with the more text, but clicking the button does not do anything.
In I do have reference
<script src="button.js"></script>
And the name of my javescript file is button.js
It should be innerHTML not innnerHTML
document.getElementById("toggleButton").innerHTML="less ⇑";
<button type="button" onclick="toggle()" id="toggleButton">more ⇓</button>
Try this ..
<input onclick="toggle()" type="button" value="more ⇓" id=myButton1"></input>
Js:
function toggle()
{
if (this.value=="more ⇓")
{this.value = "less ⇑";}
else
{this.value = "more ⇓";}
}

Execute javascript function in chain of button clicks

On my original post I wasn't for sure on the amount of depth I should go to. Here is what I have been working on since the jQuery answer was posted:
I am attempting to execute a task which requires the user to choose and click one html button out of a series of buttons and then be required to choose another html button out of a series of buttons.
Essentially I would like the value of the first button selection to be passed as a parameter to a function that will run when the user clicks the second button. I'm just learning javascript and I'm lost.
Thank you
HTML:
<form id="scoreboard">
<div>
<input type="text" name="homeTeam" value="00" size="2" "readonly" id="homeTeamScore"/>
<input type="button" value="+1" name="add1" id="homeAdd1" class="homeScore" onClick="calcScore(1)"/>
<input type="button" value="-1" name="neg1" id="homeNeg1" class="homeScore" onClick="calcScore(4)"/>
</div>
<div>
<input type="button" name="homeP1" id="homeP1" class="player" value="24" style="text-align:center;"/>
<input type="text" name="homeP1Score" value="0" size="2" style="text-align:center;"/>
</div>
<div>
<input type="button" name="homeP2" id="homeP2" class="player" value="44" style="text-align:center;"/>
<input type="text" name="homeP2Score" value="0" size="2" style="text-align:center;"/>
</div>
</form>
Javascript:
function calcScore(amount) {
if(amount==1) {scoreboard.homeP1Score.value++;scoreboard.homeTeam.value++;}
else if(amount==4) {scoreboard.homeP1Score.value--;scoreboard.homeTeam.value--;}
}
$('.player').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('.homeScore').click(function() {
function addHomeScore(data)
});
});
Using jQuery:
$('#buttonId').click(function() {
//initialize the second button listener
var data = $(this).attr('data');
$('#button2Id').click(function() {
yourFunction(data);
});
});
This method is better because it uses JavaScript scoping to avoid globals. Since JavaScript (especially with jQuery) sometimes has multiple threads/functions executing at the same time, it's very easy to run into problems with globals. They're also very hard to test and unsafe.
In raw JavaScript:
HTML:
<button class="button1" onclick="saveValue()" />
<button class="button2" onclick="callMethod()" />
JavaScript:
myGlobalVariable = null;
function saveValue(){
myGlobalVariable = "Value That Was Selected";
}
function callMethod(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
}
In jQuery:
HTML:
<button class="button1" />
<button class="button2" />
JavaScript:
myGlobalVariable = null;
$('button.button1').click(function(){
myGlobalVariable = "Value That Was Selected";
});
$('button.button2').click(function(){
alert(myGlobalVariable + "I HAZ ACCESS TO GLOBALS!!!!");
});
setup some global variable in js. then on each button setup some onClick events that go and change the global var. then the next button click can check to see the value in the global var
<button onclick="myFunction()">Click me</button>

How to make the function only runs once in javascript

How to make the function only runs once per button?
if clicks in "click me" only works once, and the same for the other buttons
Order not to put much code, I put an example..:
http://jsbin.com/apexod/1/watch
<html>
<head>
<title></title>
</head>
<body>
<input type="button" value="click me" onclick="hello()"><br>
<input type="button" value="click me1" onclick="hello()"><br>
<input type="button" value="click me2" onclick="hello()">
<script>
function hello(){
alert("hello");
}
</script>
</body>
</html>
Change your onclick handlers so that the function can reference the element clicked.
<input type="button" value="click me" onclick="hello.call(this)"><br>
<input type="button" value="click me1" onclick="hello.call(this)"><br>
<input type="button" value="click me2" onclick="hello.call(this)">
Then change the function to remove the handler.
function hello(){
alert("hello");
this.onclick = null;
}
You can just remove the onclick
<html>
<head>
<title></title>
</head>
<body>
<input type="button" value="click" onclick="hello(this)"><br>
<input type="button" value="click1" onclick="hello(this)"><br>
<input type="button" value="click2" onclick="hello(this)">
<script>
function hello(btn){
alert("hello");
btn.onclick = function(){};
}
</script>
</body>
</html>
It’s easier to manage if you add event listeners in the script (it’s also consider good practice to separate behaviour from presentation):
Demo: http://jsfiddle.net/4N4ur/
<input type="button" value="click">
<input type="button" value="click1">
<input type="button" value="click2">​
<script>
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++) {
inputs[i].onclick = function() {
hello();
this.onclick = null; // reset the handler
}
}
function hello() {
alert('hello';
}
</script>
on click of buttton call the function below with button id or name as param
<script>
function hello(caller){
if (caller == 'button1' && $("#button1clicked").val() != '1')
{
// Your code to execute for the function
alert("hello");
// set value for button1clicked
$("#button1clicked").val("1");
}else {
// do nothing
}
}
</script>
Add the above conditions for no of buttons
While the above scenario and answers are all very specific to click handlers, the answer to the original question how to make a function that only runs once is generally done using a wrapper function, similar to the UnderscoreJS .once method:
function once(fn) {
var called = false;
return function() {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
The above implementation would only allow the original function to be invoked once, and it would pass through the context and arguments of the later invocation. This would then be used as:
var oneTimeFn = once(function() {
console.log('I was called.');
});
oneTimeFn();
//-> I was called.
oneTimeFn();
//-> undefined

Return title of button being hovered on

I just want a bit of javascript to return the title of a button element that the user is hovering on. I don't want to use getElementById(...) because I am making a function that works without referring to an element but it's ID. Is this possible?
Many thanks :).
You can use this which refers to current element like this:
<input type="button" title="mytitle" onMouseOver='alert(this.title);'>
Working Example
Js
function showTitle(element){
alert( element.getAttribute('title') );
}
html
hover me
demo at http://jsfiddle.net/gaby/WKqMq/
Consider this HTML:
<input type="button" value="Button 1" />
<input type="button" value="Button 2" />
<input type="button" value="Button 3" />
<input type="button" value="Button 4" />
<input type="button" value="Button 5" />
<div id="txt"></div>
And your JavaScript that will work on any button present in the current page
$("input[type=button]").bind("hover", function() {
$("#txt").html($(this).val());
});
You may also consider looking at LIVE Example
You could also capture each button by using:
var buttons = document.getElementsByTagName("button");
for (var i=0; i < buttons.length; i++)
{
buttons[i].onmouseover = function()
{
alert(this.title);
}
}
Example: http://jsfiddle.net/2LP66/4/
This will alert the title of a button upon hovering off any button on the page.
The onmouseover function will only be run when you hover the button, but ofcourse you don't have to use an alert, you could also save the title in some more global scope and use this where you want to use the title

Categories