Cannot get button's onclick attribute to invoke JS function - javascript

I have a simple form that, in jsfiddle I've simplified even further:
https://jsfiddle.net/mvw1nt5L/
Basically I have a table with just a header row. Above it I have an "Add" button which each time it gets clicked is supposed to add a row to the table.
my button element is ...
<button id="addMeeting" type="button" onclick="addMeeting();" > Add A Meeting </button>
and the associated JS function is simply
function addMeeting() {
alert("add button clicked");
return false;
}
Real, real simple! But it doesn't work.
the JS code is contained directly in the html document as a script tag.
What am I doing wrong?
TIA for any help!
Gus

It is a conflict between an element ID on your form and the function name. Or maybe not so much a conflict as a scoping issue. I've honestly never encountered this before until I tried to solve your problem. Very strange. Here's a more detailed explanation:
Why JS function name conflicts with element ID?

it seems it's a loading and scope issue. If you place a script tag before the html it will work just fine:
<script>
function addMeeting() {
alert("add button clicked");
return false;
}
</script>
<button id="addMeeting" type="button" onclick="addMeeting()"> Add A Meeting </button>
alternatively you can also explicit use the window object:
window.addMeeting = function() {
alert("add button clicked");
return false;
}
and:
<button id="addMeeting5" type="button" onclick="window.addMeeting();"> Add A Meeting </button>

Related

Stop click function using jQuery

$("button").click(function (){
$("<button>Start</button>).appendTo('main');
});
This is my code, Now when I click a button it creates another button. But when I click it again, another button is added. I want to stop adding multiple buttons.
Please add class. You're using a generic selector. So it is the right expected behaviour. Maybe a class like .clicker something like that might work.
$("button.clicker").click(function() {
// Also you're missing a " after </button>
$("<button>Start</button>").appendTo('main');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main>
<button class="clicker">Click Me</button>
</main>

<div> class button click

I am trying to use a userscript to click a button. According to inspect element, the button looks like:
<div class="q-w-btn cl"></div>
Conveniently, the web developer neglected to put an id in there, so I was not able to select it by the id and then use the click function (are they called functions in JavaScript? I'm not an expert in the language).
I have tried many, many, many different ways, and all of them have successfully failed to click the button.
Any help is greatly appreciated, thanks for reading about my problems.
You can get elements by class name as well in java Script like below
document.getElementsByClassName("q-w-btn");
but notice that this function will return all elements in the document having the specified class name in the form of an array. As a result if your document has only one element having this class then you need to get the first element like below.
document.getElementsByClassName("q-w-btn")[0];
And yes in java script it is called functions you can see the conventions in here http://javascript.crockford.com/code.html.
Please try the following code (Insert script before </body>):
var btn = document.querySelector('.q-w-btn.cl');
if (btn) {
btn.addEventListener('click', onButtonClick);
}
function onButtonClick(evt) {
console.log('the click event is trigger');
}
You can simply use document.getElementsByClassName('q-w-btn') and bind click event on it, something like -
var button = document.getElementsByClassName('q-w-btn')[0];
button.addEventListener('click', function () {
alert('here');
});
<div class="q-w-btn">Click me</div>
This (courtesy of Ramin) worked for me:
var btn = document.getElementsByClassName("q-w-btn")[0]; btn.click();
Thanks to everyone who helped me learn and come to this solution.

JQuery function not working on element after ID has been changed

I've got a button and I want it to perform one function every odd time that it is clicked (1st, 3rd, 5th, etc) and a second function every even time that it is clicked (2nd, 4th, 6th, etc). I thought the best way to do this would be to change the id of the button and assign two JQuery functions. However, that doesn't seem to work. As you can see in this jsfiddle, when I change the id of the button, the function from the first id still gets called.
$("#search").click(function() {
alert("search clicked!");
$("#search").html("Close Search");
$("#search").attr("id", "csearch");
});
$("#csearch").click(function() {
alert("csearch clicked!");
$("#csearch").html("Search");
$("#csearch").attr("id", "csearch");
});
Why is that the case? Is it because JQuery essentially binds the function to the button when the document loads, so even though I change the id, the function is still bound?
p.s. I already found another solution to my problem, so I'm not interested in answers in that regard. Just looking to learn a little more about JQuery and Javascript.
Yes, jQuery will run through your initialization code once, when the document loads, and attach the click handlers to elements currently in the DOM. When your code runs, only the #search element exists - the $("#csearch") selector will match no elements and the click handler won't be assigned to any elements.
A jQuery object references a DOM element by reference, not by id - when you change the id of an element, a jQuery object created previously that pointed to that element will still hold a reference to the element.
If you change dynamically data in HTML you have appeal to body, because separator ('#csearch') doesnt exist after load page. Try it:
$(document).ready(function() {
$('body').on('click','#search', function() {
alert("search clicked!");
$("#search").html("Close Search");
$("#search").attr("id", "csearch");
});
$('body').on('click','#csearch', function() {
alert("csearch clicked!");
$("#csearch").html("Search");
$("#csearch").attr("id", "search");
});
})
Although you have found another way to go, a nice way to do this is to use the modulus operator (%) which can be used to return a 0 or 1.You could assign a value to the button and on the onclick - pass that value to a function where you check the returned value (ie:var number=value%2) which will give either a 0 if the number is even or a 1 if it is odd. You can then use that to direct the action of the button click - if number ==0 then do this, if it is ==1 then do that.
You then increment the count and reset the value of the button for the next click. That way you do not have to change the id of the button- you just change its behaviour. Just a thought for a method of toggling the effect of a button click :)
Look up event delegation - there's plenty of answers on SO that explain it in detail.
As for your solution - just add a data value to the button and toggle it / read it on each click. Then there's no need to change the id, so no need to change the event handler:
$("#search").click(function() {
var oddeven = $(this).data("oddeven") || 1;
if (oddeven == 1) {
alert("search clicked!");
$(this).html("Close Search");
$(this).data("oddeven", 2)
}
else {
alert("csearch clicked!");
$(this).html("Search");
$(this).data("oddeven", 1)
}
});
Updated fiddle: https://jsfiddle.net/vxn3ozzb/1/
Alternatively, you could have two buttons and toggle between them:
<button id="search" class="btn btn-default action-button shiny-bound-input" type="button">
Search
</button>
<button id="csearch" class="btn btn-default action-button shiny-bound-input" type="button" style='display:none'>
Close Search
</button>
code
$("#search").click(function() {
alert("search clicked!");
$(this).hide();
$("#csearch").show();
});
$("#csearch").click(function() {
alert("close search clicked!");
$(this).hide();
$("#search").show();
});
Fiddle: https://jsfiddle.net/vxn3ozzb/2/
You need to use event delegation, instead of binding when dealing with elements with changing selectors.
$(document).ready(function() {
$(document).on("click","#search",function() {
alert("search clicked!");
$("#search").html("Close Search");
$("#search").attr("id", "csearch");
});
$(document).on("click","#csearch",function() {
alert("csearch clicked!");
$("#csearch").html("Search");
$("#csearch").attr("id", "csearch");
});
})
Working example : https://jsfiddle.net/DinoMyte/vxn3ozzb/4/
I believe, changing the ID of an element would not be an appropriate idea for this particular scenario. Instead, it's better to use data attributes to accomplish this. For example, Instead of changing the ID, you could change the data attribute value to track it and then you can apply your logic accordingly. This way in future, if you want to add additional behaviour to the button (odd, even and somethingElse), you don't need to write an additional event handler, just need to add one more condition to the same event handler. Going forward, if the behaviours of the button are increasing, you can separate the logic out and put it into one function by passing the behaviour value to it, that way your event handler will be much cleaner and manageable.
Please suggest if anyone has a better solution.
$(document).ready(function() {
$("#search").on("click", function() {
var action = $(this).data("action");
if(action === "odd") {
$(this).data("action", "even");
alert("odd");
}
else if (action === "even") {
$(this).data("action", "odd");
alert("even");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<button id="search" data-action="odd" class="btn btn-default action-button shiny- bound-input" type="button">
Search
</button>
</div>

I have to click twice to activate function using jQuery

I am having a lot of trouble with jQuery. I have to click twice on a button to make the page disappear. I have tried importing both versions of jQuery and I tried to use the fadeOut() function on different elements, but nothing has prevailed. It works the second time I click, but never the first. This is a recurring problem, and I need to know how it can be fixed. Here is my code:
HTML:
<body>
<h1>CSS3 Buttons Showcase</h1>
Click Me!
</body>
JavaScript:
function fadeBg(){
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}
You must change your function to:
function fadeBg(){
$("body").fadeOut(1000);
}
In your HTML code onclick is being set to run your function fadeBg. So in your function you must put what you want to run; in this case $("body").fadeOut(1000);
The issue is that you're not binding the jQuery event handler until the fadeBg() function is called on the first click. Try this instead:
<h1>CSS3 Buttons Showcase</h1>
Click Me!
$(function() {
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
});
There are two ways to bind a click to an element :
1. The old dirty inline javascript (avoid)
(HTML) : <button onclick="doSomething()">
and 2. the cleaner event binding
(HTML) : <button id="myButton">
(JS) : $('#myButton').click( doSometing )
You mixed both, binding two clicks on the same element.
<button onclick="doSomething()">
function doSomething(){ // will be done on first click
$('#myButton').click( doSometingElse ) // will be done on second click
}
You are doing the same action twice, the code is:
HTML
<body>
<h1>CSS3 Buttons Showcase</h1>
Click Me!
</body>
JavaScript
$(document).ready(function() {
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}
function fadeBg(){
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
}
You added the onclick event directly in your html. This function adds a second event to the same button.
Just remove the onclick event in your element And do this:
$("#btn-1").click(function(){
$("body").fadeOut(1000);
})
It's considered bad practice adding onclick events directly in your html element. You can but it doesn't look good.

Bootstrap onClick button event

This seems a silly question but just got bootstrap and it doesn't gives any examples on the website about adding a Javascript callback to a button...
Tried setting my button an id flag and then
<div class="btn-group">
<button id="rectButton" class="btn">Rectangle</button>
<button class="btn">Circle</button>
<button class="btn">Triangle</button>
<button class="btn">Line</button>
<button class="btn">Curve</button>
<button class="btn">Pic</button>
<button class="btn">Text</button>
<button class="btn">Gradient</button>
</div>
I want to add a callback to Rectangle button...
$('#rectButton').on('show', function (e) {
//ACTION
})
cant get the point of bootstrap callbacks.
All I could found on the web is oriented to Rails + Bootstrap... no bootstrap and JS only.
There is no show event in js - you need to bind your button either to the click event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.
If, like me, you had dynamically created buttons on your page, the
$("#your-bs-button's-id").on("click", function(event) {
or
$(".your-bs-button's-class").on("click", function(event) {
methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.
$(document).on("click", "#your-bs-button's-id", function(event) {
or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {
There are many other references to this issue on stack overflow here and here.

Categories