Javascript: Run a script depending on which button is clicked - javascript

Can someone enlighten me on this please. I was trying to implement a simple Javascript function. The idea is, to run a conditional script depending on which button is clicked. Can't seem to figure this out:
<script type="text/javascript">
function whichButton(){
if(//Button 1 is clicked...){
//Run script 1
}
else if(//Button 2 is clicked){
//Run script 2
}
else if(//Button 3 is clicked){
//Run script 3
}
else if(//Button 4 is clicked){
//Run script 4
}
else{
//Do nothing
}
}
</script>
<form id="form1" onSubmit="whichButton();">
<button id="btn1">Button 1</button><br/>
<button id="btn2">Button 2</button><br/>
<button id="btn3">Button 3</button><br/>
<button id="btn4">Button 4</button><br/>
</form>
Thanks in advance!

You want to add onclick handlers to the button tags:
<script type="text/javascript">
function whichButton(buttonElement){
alert(buttonElement.id);
var buttonClickedId = buttonElement.id;
if( buttonClickedId === 'btn1' ){
// do btn1 stuff
}
else if( buttonClickedId === 'btn2' ){
// do btn2 stuff
}
// ...
else{
// don't know which button was clicked
}
}
</script>
<form id="form1" >
<button id="btn1" onclick="whichButton(this)">Button 1</button><br/>
<button id="btn2" onclick="whichButton(this)">Button 2</button><br/>
<button id="btn3" onclick="whichButton(this)">Button 3</button><br/>
<button id="btn4" onclick="whichButton(this)">Button 4</button><br/>
</form>
EDIT:
To run different code based on which button was clicked, use an IF statement similar to your original post, which I've edited above. // you can take that alert out, or move into each if/else if scope.

Pass the from to your function, then find the active element:
<form id="form1" onSubmit="whichButton(this);">
Buttons...
</form>
And the JavaScript:
function whichButton(form) {
var clicked = form.querySelector(":active");
switch(clicked.id) {
case "btn1":
// do stuff
break;
// add more cases
}
}
Note that I'm not certain about this, but I've tested it and it seems to work. Note that IE7 and older do not support :active, I have no idea how to make this work in those older versions.
EDIT: Here's a Fiddle to demonstrate.

You can try with jQuery the following:
<script type="text/javascript">
$(document).on("click", "button.btn", function(){
console.log("You clicked " + $(this).html());
return false;
});
</script>
<form>
<button class="btn">Button 1</button><br/>
<button class="btn">Button 2</button><br/>
<button class="btn">Button 3</button><br/>
<button class="btn">Button 4</button><br/>
</form>

Use AJAX to get the scripts, insert them somewhere in the DOM and use initialize() to run them.
$.get('js/script1.js', function(data) {
$('#dummydiv').html(data);
initialize();
});

Related

How to make a button disappear and reappear after 'x' seconds?

How can I make this code;
<input onclick="myFunction();" alt="click">Click Me!</button>
Hide for a few seconds, then re-appear after 'x' seconds? (This button works fine if that changes anything)
I'd like to stick with bare HTML, but if I need Javascript that's fine. No other solutions on SO work for me. Thanks.
edit:
<link rel="stylesheet" type="text/css" href="formalign.css">
<script type="text/javascript" src="trinit5.js"></script>
<button class="button" id="btn" input onclick="doSingle();" alt="Summon">Summon</button>
<img id="canvas"></img>
<div class="element"></div>
where do i embed the part?
input tag(it is standalone tag) and a button tag(it is a paired tag) and if you want a button than you can try two things:
1- assign button to the type attribute
<input type="button" id="btn" onclick="myFunction()" value="Click Me">
2-use a button tag it also has type attribute but by default button is assigned to type attribute
<button id="btn" onclick="myFunction()">Click Me!</button>
Here in the js i have written a function
JS:
<script>
function myFunction()
{
document.getElementById('btn').style.display ='none'; //first hide the button
setTimeout(function(){ //using setTimeout function
document.getElementById('btn').style.display ='inline'; //displaying the button again after 3000ms or 3 seconds
}
,3000);
}
</script>
NOTE:
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
Tip: 1000 ms = 1 second.
Tip: The function is only executed once
Hello my friend,
This can be accomplished fairly easily using a setTimeout in JavaScript. I've created a code snippet below which you can use as an example. You can change the number after the comma (1000) in the setTimeout to reflect how many thousandths of a second you want the button to have disappeared for.
Cheers and best of luck to you!
document.getElementById("button").onclick = function(){
doSingle();
document.getElementById("button").style.visibility = "hidden"
setTimeout(function(){
document.getElementById("button").style.visibility = "visible"
}, 1000)
};
function doSingle() {
// your function
};
<button class="button" id="button" alt="Summon">Summon</button>
Bare HTML won't do it I am afraid. You'll need a timer. Something like this maybe?
<button id="btn" onclick="tempInvisible(this);">Click</button>
<script>
function tempInvisible(btn) {
btn.style.display = 'none';
setTimeout(function() {
btn.style.display = 'block';
}, 10000);
}
</script>

Check what exatly button clicked, when multiple buttons with the same selector on page

I have a two buttons with the same selector class. When I do this:
$('.my_button').click(function() {
console.log(1);
});
, and then click on the button it log 1 two times, like I clicked both buttons instead single. So my question is: There exists some way in JS to get only that button what I clicked, without assign unique selector like id. I am newbien in JS, so can somebody explain me? I found related issue here. Thanks!
Edit:
I make buttons a little bit different. And yes, it returns only single button, but why click trigger works two times. Console log log two times.
Every event listener receives the event, which carries the event target. Try the below example.
$('.my_button').click(function(e) {
console.log(e);
console.log(e.currentTarget);
console.log($(e.currentTarget));
});
use this inside your function code
$('.my_button').on('click',function() {
var tempContainer=$(this).parent();
alert($(tempContainer).html()); // you ll see that you are showing the code where exists your clicked button
});
Assign different id to your buttons
$(".my_button").on("click",function(){
console.log($(this).attr("id"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="my_button" id="test" value="Test"/>
<input type="button" class="my_button" id="test2" value="Test-2"/>
Try this:
<button class="my_button">Content1</button>
<button class="my_button">Content2</button>
<script>
$( ".my_button" ).click(function( event ) {
console.log(1);
});
</script>
https://jsfiddle.net/nt9ryeyr/5/
Try this:-
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".p").click(function(e){
alert($(e.currentTarget).attr("value"));//button text on which you clicked
});
});
</script>
</head>
<body>
<input type='button' class="p" value='test'/>
</body>
</html>
if your html is like this
<button class="my_button">Test</button>
<button class="my_button">Test1</button>
then use this script
$('.my_button').click(function() {
if(this.innerHTML ==="Test")
console.log(1);
else
console.log(2);
});
or if your html is like this
<input type="button" class="my_button" value="Test"/>
<input type="button" class="my_button" value="Test1"/>
then use this script
$('.my_button').click(function() {
if($(this).val() ==="Test")
console.log(1);
else
console.log(2);
});

How to make a button visible by clicking another button?

How can I make the button save visible when I click the edit button? This is my code so far, but it happends nothing. I'm working in a jsp
<INPUT TYPE="BUTTON" VALUE="Edit" ONCLICK="btnEdit()" class="styled-button-2">
<INPUT TYPE="BUTTON" VALUE="Save" ONCLICK="btnSave()" class="styled-button-2" style="visibility:hidden;" id="save">
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementsById("save").style.visibility="visible";}
}
</script>
DEMO
It is considered bad practice to add onclick in your html, and you miss-spelled a method. You should equally avoid adding your css in your html as well.
HTML:
<INPUT TYPE="BUTTON" VALUE="Edit" class="styled-button-2" id="edit">
<INPUT TYPE="BUTTON" VALUE="Save" class="styled-button-2" id="save">
JS:
var edit = document.getElementById("edit");
var save = document.getElementById("save");
edit.onclick = function() {
save.style.visibility = "visible";
}
CSS:
#save {
visibility: "hidden";
}
Must be a long day.
You have a misspelling.
Not right
document.getElementsById
Right Way
document.getElementById
document.getElementById("save").style.visibility="visible";
use getElementById not getElementsById
Probably a simple error, but you wrote getElementsById not getElementById, which meant you were trying to get more than one element, when infact you only need to get the "save" button.
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementById("save").style.visibility="visible";}
}
</script>
Side note: You may want to tidy your code:
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
document.getElementById("save").style.visibility="visible";
}
</script>

localStorage clears screen

I'm testing out localStorage to see if it can be used in my app, but when I try to store data from a text input box to it, the screen goes blank. How can I fix this? Here is the code:
<html>
<head>
<script type="text/javascript">
function write() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display').innerHTML = data;
}
</script>
</head>
<body>
<input id="input" type="text" />
<button type="button" onclick="write()">
Write
</button>
<p id="display">
Display
</p>
<button type="button" onclick="read()">
Read
</button>
</body>
</html>
change your function name from write to something else. it sounds like you are accidentally invoking document.write, which would blank out your entire page.
You cannot use a function called write on the global (document) namespace ... call it something else and it works fine
<input id="input" type="text" />
<button type="button" onclick="somethingelse();">
Write
</button>
<p id="display1">
Display
</p>
<button type="button" onclick="read()">
Read
</button>​
function somethingelse() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display1').innerHTML = data;
}​
Working example here
The code inside html event handlers is ran effectively like:
with(document) {
with(this) {
write();
}
}
so your write is shadowed (it calls document.write). You can simply refer to the correct write with window.write():
<button type="button" onclick="window.write()">
Ultimately it's better not to use inline html events at all. A simple button.onclick = write would have worked, where button is reference to the element.

onClick to get the ID of the clicked button

How do find the id of the button which is being clicked?
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
}
You need to send the ID as the function parameters. Do it like this:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
This will send the ID this.id as clicked_id which you can use in your function. See it in action here.
In general, things are easier to keep organized if you separate your code and your markup. Define all of your elements, and then in your JavaScript section, define the various actions that should be performed on those elements.
When an event handler is called, it's called within the context of the element that was clicked on. So, the identifier this will refer to the DOM element that you clicked on. You can then access attributes of the element through that identifier.
For example:
<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>
<script type="text/javascript">
var reply_click = function()
{
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>
USING PURE JAVASCRIPT:
I know it's late but may be for the future people it can help:
In the HTML part:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
In the Javascipt Controller:
function reply_click()
{
alert(event.srcElement.id);
}
This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.
(I think the id attribute needs to start with a letter. Could be wrong.)
You could go for event delegation...
<div onClick="reply_click()">
<button id="1"></button>
<button id="2"></button>
<button id="3"></button>
</div>
function reply_click(e) {
e = e || window.event;
e = e.target || e.srcElement;
if (e.nodeName === 'BUTTON') {
alert(e.id);
}
}
...but that requires you to be relatively comfortable with the wacky event model.
<button id="1" onClick="reply_click(this)"></button>
<button id="2" onClick="reply_click(this)"></button>
<button id="3" onClick="reply_click(this)"></button>
function reply_click(obj)
{
var id = obj.id;
}
How to do it without inline JavaScript or external libraries
it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it.
Here is my way of attaching events to buttons.
I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.
Modern browsers (2015+)
Works before the document has finished loading.
Very efficient.
Separates JS from HTML.
JS is in the <head>
const Listen = (doc) => {
return {
on: (type, selector, callback) => {
doc.addEventListener(type, (event)=>{
if(!event.target.matches(selector)) return;
callback.call(event.target, event);
}, false);
}
}
};
Listen(document).on('click', '.btn', function (e) {
let div = document.createElement("div");
div.innerHTML = "click " + e.target.id + "!";
document.body.appendChild(div);
});
<button id="b1" class="btn">Button 1</button>
<button id="b2" class="btn">Button 2</button>
<button id="b3">Do nothing</button>
2014 browsers only
<button class="btn" id="b1">Button</button>
<script>
let OnEvent = (doc) => {
return {
on: (event, className, callback) => {
doc.addEventListener('click', (event)=>{
if(!event.target.classList.contains(className)) return;
callback.call(event.target, event);
}, false);
}
}
};
OnEvent(document).on('click', 'btn', function (e) {
window.console.log(this.id, e);
});
</script>
2013 browsers only
<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
var hasClass = function(el,className) {
return el.classList.contains(className);
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script>
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Cross-browser
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Cross-browser with jQuery
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
$(document).on('click', '.click-me', function(e){
doSomething.call(this, e);
});
})(jQuery);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.
Here is a jsfiddle
For some strange reason the insertHTML function does not work in it even though it works in all my browsers.
You can always replace insertHTML with document.write if you don't mind it's drawbacks
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>
Sources:
What are alternatives to document.write?
Check if an element contains a class in JavaScript?
event.preventDefault() function not working in IE
https://gist.github.com/eduardocereto/955642
<button id="1" class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>
<script>
$('.clickMe').click(function(){
alert(this.id);
});
</script>
If you don't want to pass any arguments to the onclick function, just use event.target to get the clicked element:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
// event.target is the element that is clicked (button in this case).
console.log(event.target.id);
}
With pure javascript you can do the following:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}​
check it On JsFiddle
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
console.log(window.event.target.id)
}
You can simply do it this way:
<input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
<script type="text/javascript">
function showId(obj) {
var id=obj;
alert(id);
}
This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)
function reply_click(e) {
console.log(e.target.id);
}
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
Button 1 Button 2 Button 3
var reply_click = function() {
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
<button id="1"class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>
$('.clickMe').live('click',function(){
var clickedID = this.id;
});
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.
in your case:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
This will log the id of the element that's been clicked: addFields.
<button id="addFields" onclick="addFields()">+</button>
<script>
function addFields(){
console.log(event.toElement.id)
}
</script>
Although it's 8+ years late, in reply to #Amc_rtty, to get dynamically generated IDs from (my) HTML, I used the index of the php loop to increment the button IDs. I concatenated the same indices to the ID of the input element, hence I ended up with id="tableview1" and button id="1" and so on.
$tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";
In the javascript, I stored the button click in a variable and added it to the element.
function loadDoc(e) {
var btn = e.target.id;
var xhttp = new XMLHttpRequest();
var page = document.getElementById("tableview"+btn).value;
//other Ajax stuff
}
Sorry its a late answer but its really quick if you do this :-
$(document).ready(function() {
$('button').on('click', function() {
alert (this.id);
});
});
This gets the ID of any button clicked.
If you want to just get value of button clicked in a certain place, just put them in container like
<div id = "myButtons"> buttons here </div>
and change the code to :-
$(document).ready(function() {
$('.myButtons button').on('click', function() {
alert (this.id);
});
});
I hope this helps

Categories