Onclick Event Javascript & JQuery - javascript

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.

Related

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

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>

jquery javascript click function from within a function

I have an external JS file that contains the following jQuery code:
var globalNames = { next: 'input[name="next"]'};
var globalElements = { next: $e.find(globalNames.next) };
initQuiz: function() {
globalElements.next.click(function () {
if (y.forcingQuestionSolve && !j[c.index()] && (y.quizSummeryHide || !y.reviewQustion)) {
alert(WpProQuizGlobal.questionNotSolved);
return false
}
i.methode.nextQuestion()
}
);
the globalElements.next.click function is triggered by a click on a button:
<input type="button" name="next" value="Next" class="Button" ">
What I would like to do is call this p.next.click function from a Input Checkbox click.
I have added the following code:
<script>
$(document).on("click", "input[class='questionInput']", function () {
alert("Thanks for checking me");
// This is the line I'm not sure off !?!?
$('next').trigger('click');
});
</script>
As you can see, I have tried to call the trigger event but its not working.
I have to note that the 2 jQuery statements are not combined in document, they are separate.
EDIT: Added Correct Variables (global*)
Hi i think you only forgot to dedicate the button which has to be triggered.
<script>
$(document).on("click", "input[class='questionInput']", function () {
alert("Thanks for checking me");
// This is the line I'm not sure off !?!?
$('[name=next]').trigger('click');
// $('.Button').trigger('click');
});
thanks everyone.. I used the following code from Calvin Nunes-
$("[name='next']").trigger('click');
Craig.

Why does the onclick fire next function not assigned to it?

Why clicking the button fires the alert? It is assigned to the paragraph, not button.
HTML:
<button onclick="foo()">Click me</button>
<p id="hidden" style="display:none"> I was hidden </p>
Javascript:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick();
}
function innnerClick(){
alert("Ouch! That hurt!")
}
Because of this line:
// ----------------------------------------------------vv
document.getElementById("hidden").onclick = innnerClick();
Here you call the innnerClick function immediately.
Just remove () after to pass the reference to a function instead of calling it, i.e.
document.getElementById("hidden").onclick = innnerClick;
Since, you need to add the reference of the function like this:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick;
}
not directly calling it.
Fiddle Demo
In jQuery, we can reproduce the same issue like:
$('button').click(function () {
$('#hidden').show();
$('#hidden').click(innnerClick()); <-- see the function with () here
});
Fiddle Demo
The issue is same here, we just need to pass the function reference to click handler here like:-
$('#hidden').click(innnerClick);
Fiddle Demo

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