I want to call two functions from one onclick [duplicate] - javascript

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?

This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.

There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}

You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>

You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Related

Onclick Event Javascript & JQuery

I have the following code snippets in my main.js file
function one(){
//some code
var btn = "<button type='submit' id='processReceipt' class='btn btn-primary' onclick='form_new_receipt()'>Submit</button>";
document.querySelector('#showGrower').innerHTML += btn;
}
The function the submit button is calling is below
$(document).ready(function() {
// Do your event binding in JavaScript, not as inline HTML event attributes:
$("#processReceipt").on("click", form_new_receipt);
function form_new_receipt() {
alert('before function');
}
});
What could I be missing because the alert does not show up - meaning the function is not being called.
I had tried this below but it didn't work - that's why I added the $(document).ready
function form_new_receipt() {
alert('before function');
}
Is this what are you looking for?
function one(){
var btn = "<button type='submit' id='processReceipt' class='btn btn-primary' onclick='form_new_receipt()'>Submit</button>";
$('#showGrower').append(btn);
}
$(document).on('click', '#processReceipt', function() {
one()
});
function form_new_receipt(a) {
alert('before function');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showGrower"></div>
<button id="processReceipt" type="button">Click me</button>
You are missing to call one(), Please see below code
<div id="showGrower"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function one(){
var btn = "<button type='submit' id='processReceipt' class='btn btn-primary' onclick='form_new_receipt()'>Submit</button>";
document.querySelector('#showGrower').innerHTML += btn;
}
$(document).ready(function() {
one(); // Call one() function
$("#processReceipt").on("click", form_new_receipt);
function form_new_receipt() {
alert('before function');
}
});
</script>
what is the problem? what the expected behavior? what the current non-expected behavior? btw you don't need to put onclick="" in the html if you add it later on with jQuery. anyway, your code has two conceptual problems:
if you want to use jQuery, you have to bind it once the element is created:
function one(){
//some code
var btn = "<button type='submit' id='processReceipt' class='btn btn-primary'>Submit</button>";
document.querySelector('#showGrower').innerHTML += btn;
$("#processReceipt").on("click", function form_new_receipt() {
alert('before function');
}
}
if you want to use onclick inside html you have to declare the function in the global scope
function form_new_receipt() {
alert('before function');
}
you could also create the element with
var a = document.createElement('button');
and assign properties programmatically
a.type = 'submit';
...
that is significantly faster and allows you to bind events like
a.addEventListener('click', (eventArg) => {
alert('hello!');
}
No need for vanillaJS since you're using the jQuery you could also it will be better to prevent the use of inline-event's as onclick and attach your click event just from the jQuery code like the following snippet shows.
Hope this helps.
$(document).ready(function() {
one();
});
function one(){
$('#showGrower').append("<button type='submit' id='processReceipt' class='btn btn-primary'>Submit</button>");
$("#processReceipt").on("click", form_new_receipt);
}
function form_new_receipt() {
alert('before function');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="showGrower"></span>
If you want to bind the click handler in javascript, you need to set the click handler after adding the button to DOM.
You can add the click handler inside the one() function. (I have removed the onclick attribute from the button).
function one(){
//some code
var btn = "<button type='submit' id='processReceipt' class='btn btn-primary'>Submit</button>";
document.querySelector('#showGrower').innerHTML += btn;
$("#processReceipt").on("click", form_new_receipt);
function form_new_receipt() {
alert('before function');
}
}
Alternatively, what you can do is you can attach the click handler to a parent static element like body
$(document).ready(function() {
// Do your event binding in JavaScript, not as inline HTML event attributes:
$('body').on("click", "#processReceipt", form_new_receipt);
function form_new_receipt() {
alert('before function');
}
});
And of course you don't want to forget to call one() function.
Link to jsfiddle for both cases:
https://jsfiddle.net/jej453se/
https://jsfiddle.net/jej453se/1/
First: why do you wan to create 2 kinds of code (plain javascript and jquery). You can achieve what you desire with only 1 type.
But still, taking your code, I have created a codepen.
Please try, it works:
https://codepen.io/vishalkaului/pen/ZapXpG
The issue why it wasn't working was you were not executing the function one. I have changed it to an IIFE which would run automatically without being called explicitly.

Pass a reference of the button I'm clicking into the func it triggers. JS

How do I pass a reference of the button I am clicking into the function it triggers?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this??);
return false;
})
var myFunc = function (this??) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(this??).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
I can't use the class name as there are several of these buttons on my page.
Use myFunc(this). Its correct way to passs the element to your function
Use any other name other than this for your function parameter.
jQuery('<button class="btn"/>')
.click(function () {
myFunc(this);
return false;
});
var myFunc = function (elem) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if (jQuery(elem).parent().hasClass('myClass')) {
//DO STUFF HERE
}
}
No need to pass it in a separate function
jQuery('<button class="btn"/>')
.click(function() {
if(jQuery(this).parent().hasClass('myClass')){
//DO STUFF HERE
}
return false;
})
Remove ?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this);
return false;
})
var myFunc = function (obj) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(obj).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
this is a reserved word and cannot be used as a variable (which is what you're attempting to do within your myFunc function. Change the name of your variable in your myFunc declaration:
var myFunc = function (myElement) { ... }
Then change your if statement to reflect that change:
jQuery(myElement).parent().hasClass('myClass')
I dont have much knowledge about jquery but a possible solution using Js is
<script>
function onClick1(b)
{
alert(b.parentNode.className);
}
</script>
<div class="divClass">
<button onclick="onClick1(this)">
hello
</button>
</div>
we can pass "this" in the onclick event attribute, which passes the reference object of the element generating the event (in this case button). We then can reference the parentNode of button and its class with className property.
HTML
<div class="myClass">
<button id="btn" class="btnClass">Hi</button>
</div>
JS
$('.btnClass').click(function() {
myFunc(this);
});
var myFunc = function (a) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(a).parent().hasClass('myClass')){
alert();
//DO STUFF HERE
}
}
Check This Example

Set onclick event using script

I want to make my script set the onclick properity of a <div>.
I use this Html code:
<div id="forgotpass">Forgot Password?</div>
I want when a user clicks the <div> a forgotpass() function to run, but I do not want to use this:
<div id="forgotpass" onclick="forgotpass();">Forgot Password?</div>
Alternatively, if you're not using jQuery:
document.getElementById('forgotpass').onclick = forgotpass;
Pure JavaScript:
function addListener(element, eventName, handler) {
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent('on' + eventName, handler);
}
else {
element['on' + eventName] = handler;
}
}
function removeListener(element, eventName, handler) {
if (element.addEventListener) {
element.removeEventListener(eventName, handler, false);
}
else if (element.detachEvent) {
element.detachEvent('on' + eventName, handler);
}
else {
element['on' + eventName] = null;
}
}
addListener(document.getElementById('forgotpass'), 'click', forgotpass);
jQuery:
$(document).ready(function() {
$("#forgotpass").click(forgotPass);
});
Or:
$(document).ready(function() {
$("#forgotpass").click(function() {
forgotPass();
});
});
Something like this might work..
var div = document.getElementById("forgotpass");
div.onclick=function(){ /*do something here */ };
if you dont add the function, the javascript will run the onclick once it runs through the script.
You can do it with jQuery like
$("#forgotpass").click(function() {
alert("Handler for .click() called.");
});
In pure javascript you can do:
function forgotpass() {
//..code
}
var el = document.getElementById("forgotpass");
el.onclick = forgotpass;
but this is very naive, not flexible and probably a bad practice.
If you are using jQuery, you can do:
function forgotpass() {
//..code
}
$(document).ready(function() {
$("#forgotpass").click(function() {
forgotPass();
});
});
If you only need to support IE 9+ (source), you can use EventTarget.addEventListener in pure JavaScript.
function forgotpass() {
alert("Hello, world!");
}
var element = document.getElementById("forgotpass");
element.addEventListener("click", forgotpass, false);
<button id="forgotpass">Forgot Password?</button>
If you need to support older browsers, I recommend Speransky Danil's answer.
Adding event-listner directly in the HTML :
...
<div>
<input type="button" value="Set Cookie" onclick="setCookie();" />
</div>
<script>
function setCookie() {
console.log('ready to set cookie?');
}
</script>
...
Reference : W3CSchools
Good Luck!
If you are using jQuery it's best if done as follows. If the function call is executed more than once multiple eventhandles will be registered. Following approach makes sure the previous handlers are removed
$("#forgotpass").off().on('click', function () {
forgotPass();
});

Calling javascript function

I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.

Can I have two JavaScript onclick events in one element?

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Categories