onClick to get the ID of the clicked button - javascript

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

Related

How would you write this jQuery code that binds a clicked element to functions in JavaScript?

I have being trying to solve a problem of how to bind a clicked element to functions using JavaScript, and after many days finally found a solution here provided by #JerdineSabio. My original problem was asked at Stackoverflow and it had to do with a single JavaScript script handling many buttons and performing speech recognition. The code that binds the clicked button to the functions is written in jQuery and involves using function(e) . The jQuery statement takes 3 parameters, but in JS the equivalent expression only takes two (the event (eg. the clicking) and the function). I've looked up the usual references I depend upon but haven't found a way to write it in Javascript. I have solved the scripting problem; so I just want to find an answer to this question in case I might want to use JS only in the future, as I tend to rely on JS more than jQuery, and I also read about function(e) before and watched a video on Youtube about it, but I still did not quite understand what "e" is and what it does.
The jQuery script below works as it should. The code changes the color of the button that's next to it. Once again, this involves multiple buttons but there is only one script for them all.
I have tried:
document.addEventListener("click", myFunction);
function myFunction(e) {
this.previousElementSibling.setAttribute("style", "background-color: gold") ...
....};
and I've tried a few more things, but I can't make the function work correctly no matter what I try.
The HTML is:
<div class="container">
<button id="first" type="button" class="btn btn-danger"></button>
<button id="first" type="button" class="btn btn-warning"></button>
</div>
The jQuery is:
$(document).ready(function(){
$(document).on("click", "#first", function(e) {
$(this).siblings().css("background-color", "gold");
});
});
You can do in many ways by adding onclick function to the button then target them by id or class name
First by the id (ofc must have unique id) then you gonna put :-
function btnClicked(clicked_btn) {
let btn = document.getElementById(clicked_btn)
btn.style.backgroundColor = 'red'
}
<div class="container">
<button id="first" onClick='btnClicked(this.id)' type="button" class="vtn btn-danger">press1</button>
<button id="second" onClick='btnClicked(this.id)' type="button" class="btn btn-warning">press2</button>
</div>
second by class name :- but you have more than class name so we gonna add split() function to target one of them like so
function btnClicked(clicked_btn) {
let btn = document.querySelector('.' + (clicked_btn.split(' ')[1]))
btn.style.backgroundColor = 'red'
}
<div class="container">
<button id="first" onClick='btnClicked(this.className)' type="button" class="btn btn-danger">press1</button>
<button id="second" onClick='btnClicked(this.className)' type="button" class="btn btn-warning">press2</button>
</div>
You can try this way:
<script>
window.addEventListener('load', () => {
var buttons= document.querySelectorAll('#first');
for (var i = 0; i < buttons.length; i++)
buttons[i].addEventListener("click", myFunction);
});
function myFunction(e) {
siblings(e.target).forEach((element, index) => {
element.setAttribute("style", "background-color: gold")
});
};
function siblings(elem) {
let siblings = [];
if (!elem.parentNode)
return siblings;
let sibling = elem.parentNode.firstElementChild;
do {
if (sibling != elem)
siblings.push(sibling);
} while (sibling = sibling.nextElementSibling);
return siblings;
};
</script>
Basic event delegation requires you to have to figure out what was clicked is the element you are looking for. Using matches() makes that easy.
function delegatedClick(selector, callback) {
function fnc(event) {
if (event.target.matches(selector)) {
callback.call(event.target, event);
}
}
document.addEventListener("click", fnc);
}
delegatedClick(".foo button", function() {
console.log(this.id);
});
.foo button {
color: green;
}
<div class="foo">
<button type="button" id="b1">Yes</button>
</div>
<div class="foo">
<button type="button" id="b2">Yes</button>
</div>
<div class="bar">
<button type="button" id="b3">No</button>
</div>
<div class="foo">
<button type="button" id="b4">Yes</button>
</div>
Now toggling the siblings
var wrapper = document.querySelector(".foo");
var buttons = wrapper.querySelectorAll("button")
wrapper.addEventListener("click", function (event) {
var clickedButton = event.target.closest("button");
clickedButton.classList.remove("goldbg");
buttons.forEach(function (btn) {
if (btn !== clickedButton) {
btn.classList.add("goldbg");
}
});
});
.foo button.goldbg {
background-color: gold;
}
<div class="foo">
<button type="button" id="b1">1</button>
<button type="button" id="b2">2</button>
<button type="button" id="b3">3</button>
<button type="button" id="b4">4</button>
</div>

Add a second button after first is clicked in JS

I need help with adding a second button "Proceed" to appear only after "I Agree" button is clicked by the user. The "Proceed" button should take the user to a specific URL. https://www.google.com for example.
<!DOCTYPE html>
<html>
<body>
<p> Click following button to agree to the terms and conditions.</p>
<p id="demo" style="color:white">User Agreed to terms and conditions.</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "I Agree";
}
</script>
<button onclick="myFunction()">I Agree</button>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.color = "green";
}
</script>
</body>
</html>
Try something like this:
function agree() {
document.getElementById("proceed").style.display = "block";
}
<!DOCTYPE html>
<html>
<body>
<p> Click following button to agree to the terms and conditions.</p>
<button onclick="agree()">I Agree</button>
<a id="proceed" style="display: none;" href="https://www.google.com">Proceed</a>
</body>
</html>
You can make a new button using the document.createElement method, then give it some properties and append it to a parent element in the DOM.
You can navigate to a new page using the location property of the (default) window object. (Note that the line that handles browser navigation is commented out below because Stack Overflow snippets are sandboxed so the code would fail in this environment.)
This demo uses a "buttonContainer" div that is responsible for handling clicks on its child buttons, calling the appropriate function in each case.
const buttonsContainer = document.getElementById("buttons-container");
buttonsContainer.addEventListener("click", handleButtonClicks);
function handleButtonClicks(event){
if(event.target.id == "agree-btn"){ addProceedBtn(event); }
else if(event.target.id == "proceed-btn"){ proceed(event); }
}
function addProceedBtn(event){
const
proceedBtn = document.createElement("button");
proceedBtn.id = "proceed-btn";
proceedBtn.textContent = "Proceed";
buttonsContainer.appendChild(proceedBtn);
}
function proceed(event){
console.log("We got one!");
// location = "https://my-other-page.com"; // Redirects browser
}
<p> Click following button to agree to the terms and conditions.</p>
<div id="buttons-container">
<button id="agree-btn">I Agree</button>
</div>
In this code, there is a hidden button when page is loaded. After you click the "Agree" button, "Proceed" button will be appeared.
<!DOCTYPE html>
<html>
<body>
<p> Click following button to agree to the terms and conditions.</p>
<p id="demo" style="color:white">User Agreed to terms and conditions.</p>
<button onclick="myFunction()">I Agree</button>
<button id="proceed-button" onclick="window.location.href = 'http://www.google.com'" style="display:none">Proceed</button>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.color = "green";
document.getElementById("proceed-button").style.display = 'inline-block';
}
</script>
</body>
</html>
try like this
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="check">
<p> Click following button to agree to the terms and conditions.</p>
<p id="demo" style="color:white">User Agreed to terms and conditions.</p>
<button id="btn" onclick="myFunction()">Proceed</button>
<script>
document.querySelector('#btn').setAttribute("disabled", "disabled");
document.querySelector('#check').addEventListener('click', function(event) {
console.log(event.srcElement.checked);
if(event.srcElement.checked) {
document.querySelector('#btn').removeAttribute("disabled");
} else {
document.querySelector('#btn').setAttribute("disabled", "disabled");
}
})
function myFunction() {
var x = document.getElementById("demo");
x.style.color = "green";
}
</script>
</body>
</html>

How to make every element click trigger another click on another element

I tried to use jQuery to make a click on a specific element trigger another click on another element,
that was my code:
jQuery( ".menu-item menu-item-type-custom menu-item-object-custom
menu-item-37" ).click(function() {
jQuery(
".elementor-tab-title-2261" ).click(); });
You're logic appears to be correct, I'm assuming the class selectors you're using are not targeting the right elements, jQuery isn't being initialized, or there is an error earlier in the code that prevents this part of the code from running.
Check out this working code I wrote and compare it to what you have:
$('#btn2').on('click', function() {
console.log('btn 2 clicked!');
});
$('#btn1').click(function() {
$('#btn2').click();
});
.button {
padding: 16px;
margin: 5px;
background-color: lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="btn1" class="button">
<p>
Button one
</p>
</div>
<div id="btn2" class="button">
<p>
Button two
</p>
</div>
In javascript, it can be achieved through dispatchEvent
const btn1 = document.querySelector('#btn1');
const btn2 = document.querySelector('#btn2');
const event = new Event('click');
btn1.addEventListener('click', function(e) {
e.preventDefault();
console.log('Button 1 clicked');
btn2.dispatchEvent(event);
});
btn2.addEventListener('click', function(e) {
e.preventDefault();
console.log('Button 2 clicked');
});
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
jQuery
$('#btn1').on('click', function(e) {
e.preventDefault();
console.log('Button 1 clicked');
$('#btn2').click();
});
$('#btn2').on('click', function(e) {
e.preventDefault();
console.log('Button 2 clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
Here is a more generalized way to do that not trigger only a click.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function myFunction(){
$(".b").trigger("click");
}
$(".a").click(function(){
$(".a").hide();
myFunction();
});
$(".b").click(function(){
$(".b").hide();
});
});
</script>
</head>
<body>
<p class="a">Click me away!</p>
<p class="b">Click me too!</p>
</body>
</html>

page reloads when using document.getElementById

Im using the js function shown below to make a part of page disappear when user clicks on the button.
but when i click on the button, the part does disappear, but then page reloads.
why is it like this?
<button id="myDIV" onclick="fncShowHide()">Try it</button>
<script>
window.fncShowHide = function() {
document.getElementById("idein").className = "display-none";
}
</script>
See What's the standard behavior when < button > tag click?.
Return false from the onclick handler to prevent any default browser action.
<button id="myDIV" onclick="fncShowHide(); return false;">Try it</button>
?
window.fncShowHide = function() {
document.getElementById("idein").className = "display-none";
}
window.other_ = function() {
document.getElementById("idein").style.display = "none";
}
.display-none{
display:none;
}
<button id="myDIV" onclick="fncShowHide(); return false;">Try it</button>
<div id="idein">BYEEEEEEEEEEEEEEEEEEEEEEEEEEE!</div>
<script>
</script>

Javascript: Run a script depending on which button is clicked

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();
});

Categories