Click on button with jQuery doesn't have action [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I'm stuck with an button, and can't understand why it isn't work.
$('#full-london').on('click', () => {
weatherPage.render('London');
});
'#full-london' is id of my button
weatherPage.render starts some jQuery code witch change my front page. This is tested in other case and it work correct.
This is the button:
<a id="full-london" class="btn btn-dark">Full forecast</a>
Any idea what is wrong?
Here is additional situation with search button who uses weatherPage.render and it work:
$('#search-city-button').on('click', () => {
const searchString = $('#search-city-input').val();
weatherPage.render(searchString);
});
searchString is search input
<div id="search">
<input type="text" id="search-city-input">
<a id="search-city-button" class="btn btn-danger">Search</a>
</div>
Here is what is weatherPage.render(); do https://pastebin.com/PLgrrYQ0

that makes perfect sense!!
you're adding your button dynamically, so when JS is parsing $('#full-london').on('click',... at that time there's no button on the page, so it can't attach the event to it.
function setEvents() {
$('#full-london').on('click', () => {
weatherPage.render('London');
});
}
make a function inside of your JS module (like setEvents) and call that function AFTER you add button to the page.

Related

Toggle attribute and css data [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am trying to make a follow button - and when clicked it sends an ajax request to my backend script and if it executes it returns a value that triggers the button's text to go from "follow" to "following" - and that part works just fine. But the jquery part where I send the user data in a data-attribute "data-follow" won't toggle with "data-unfollow". It only works when you refresh the browser which means you can only click the follow button, see it and the data attribute to change to "unfollow" but if you click once more it does not work. I cant figure it out and i've done my searching at the stack.
ERROR
TypeError: $(...).attr(...) is undefined
HTML
<button id="follow" data-follow="1, username1, username2">
<div><img src="images/loggedin/follow.png"></div>
<div>Follow</div>
</button>
JQuery
$("button[data-follow]").click(function(){
var button = $(this);
var data = $(this).attr("data-follow").split(",");
alert(data);
button.find(" > div:last-child").animate({opacity: "0"},200, function(){
$(this).animate({opacity: "1"},200);
$(this).html("Following");
var dataValue = $(this).closest("#follow").attr("data-follow");
$(this).closest("#follow").attr("data-unfollow", dataValue);
$(this).closest("#follow").removeAttr("data-follow");
});
});
$("button[data-unfollow]").click(function(){
var button = $(this);
var data = $(this).attr("data-unfollow").split(",");
alert(data)
button.find(" > div:last-child").animate({opacity: "0"},200, function(){
$(this).animate({opacity: "1"},200);
$(this).html("Follow");
var dataValue = $(this).closest("#follow").attr("data-unfollow");
$(this).closest("#follow").attr("data-follow", dataValue);
$(this).closest("#follow").removeAttr("data-unfollow");
});
});
$(document).on('click', 'button[data-follow]', function() {...});
$(document).on('click', 'button[data-unfollow]', function() {...});
Try it this way.
More Generic answer!
You can simply change the state of a button by removing, adding and toggling css classes via jQuery.
At (document.ready) check if follwing or unfollowed state via your ajax request and change the button's css class.
if(following){
$("#buttonID").toggleClass('following_btn');
} else{
$("#buttonID").toggleClass('unfollowing_btn');
}
Once clicked, process your code in the web service. Follow if unfollowed or Unfollow if followed. Then if you're rturning the updated state use that to re-update your button's css class accordingly. Or perform ajax call to verify the new state after the button click's ajax call finishes.
CSS:
.following_btn{
//your following style
}
.unfollowing_btn{
//your un-following style
}
Hope it helps!

Javascript not being called when event fires (Only with $(document).ready) [duplicate]

This question already has answers here:
Does ID have to be unique in the whole page?
(14 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I have a JS code in my WebApp and it's supposed to be triggered when I click a anchor and in fact it is, but only if I also use with $(document).ready.
If I use only the click event the script is not executed, but if I insert one more line in the JS file with $(document).ready the script is invoked as soon as the page load and also when I click the button. My intention in to call that script only when this particular button is clicked but I can't find a way to achieve this. Can you guys help?
<c:forEach items="${prontuario.atendimentos}" var="atendimento">
<li> ${atendimento.preenchimentoModeloAtendimento} ${atendimento.dataAtendimento} ${atendimento.tipoDeAtendimento.custo}
</c:url>"><i class="fa fa-arrow-circle-o-down fa-2x"></i>
<a id="aEditaAtendimento" href="<c:url value="/prontuario/editarAtendimento/${prontuario.prontuarioId}/${atendimento.atendimentoId}"></c:url>"><i class="fa fa-arrow-circle-o-down fa-2x"></i></a>
</li>
</c:forEach>
var abreEdicaoAtendimento = function() {
var idAtendimento = $('#idAtendimento').text();
var botaoAbreModal = $('#btnEditarAtendimento');
var campoIdPersistir = $('#atendimentoId');
alert(idAtendimento);
if (idAtendimento !== null) {
campoIdPersistir.val(idAtendimento);
botaoAbreModal.click();
} else {
alert('else');
}
};
$('#aEditaAtendimento').click(abreEdicaoAtendimento);
$(document).ready(abreEdicaoAtendimento);

Uncaught ReferenceError: printProducts is not defined [duplicate]

This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 6 years ago.
I keep getting this error when i inspected the element of my button. The button is suppose to give a print view to page.
HTML Code:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
Javascript Code:
function printProducts(){
window.print();
}
Attached here is my code live in jsFiddle:
https://jsfiddle.net/PochMendoza/scj0q0dk/
"In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers."
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
---Niet The Dark Absol
For your example, you want to define the onclick method of a button. That's really easy with JavaScript, we just need to give the button an id in the HTML, so that we can find it in our JavaScript code.
Change this:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
To this:
<button id="myButton" class="hidden-print">Print Products</button>
Note that we no longer need the onclick="printProducts()" part anymore.
Now we need to set the printProducts function to run when the button is clicked. This can be done like so:
document.getElementById('myButton').onclick = printProducts;
Start edit
This code needs to be placed in the onload function though, to properly run.
Do that like so:
window.onload = function() {
document.getElementById('myButton').onclick = printProducts;
}
End edit
And the printProducts function remains the same.
Working JSFiddle
document.getElementById('myButton').onclick = printProducts;
function printProducts(){
window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>

trying to target a button created by JQuery [duplicate]

This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 7 years ago.
I'm trying to target a button I've created by pressing another button. My code technically works, but due to the size of what I'm doing, I'm trying to put the function of the second button press in another js file. That where I'm running into problems. My code is below.
$("#webCoding").on("click", function() {
if ( $( ".webCodingID" ).length ) {
return false;
}
picture.attr("src", "img/webCoding.jpeg");
$(".target").empty();
$(".jumbotron").hide();
var buttonGroup = $('<div role="group" aria-label="...">').addClass('btn-group-vertical center-block')
var buttonPhilosophy =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Design Philosophy")
var buttonStack =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Visit My Stack Overflow Account")
var buttonGithub =$("<button type='button' id='git'>").addClass("btn btn-default btn-lg").append("Look at what I've been doing on Github")
var webCodingID =$("<div>").addClass("trainingID")
$(buttonGroup).append(buttonPhilosophy).append(buttonGithub).append(buttonStack);
$('.target').append(buttonGroup).append(webCodingID);
// code for pressing created button is below.
$("#git").on("click", function() {
prompt("herro");
});
});
but I put this in another file (and get rid of the same code in the original js file), and nothing happens.
$(document).ready(function(){
$("#git").on("click", function(){
prompt("jungle boogie");
});
I can't figure out why. The js file is linked to my main page, I just can't get it to recognize buttons created by JS in another file.
You should bind the on to the body like so:
$("body").on("click", "#git", function(){
That should solve your problem I believe :)

How to set ButtonState Loading in HTML5 CSHTML Page

Here is my HTML entry that fires the GenerateBill() Javascript at the moment :
<a class="btn btn-primary" id="loading-example-btn" data-loading-text="Loading..." onclick="GenerateBill()">Generate Bill</a>
Here is the GenerateBill() method, this all works fine, all I want to do is add the button state feedback
function GenerateBill() {
var url = '/PremiseProvider/GenerateBill';
var data = {
StartDate: $('#from').val(),
EndDate: $('#to').val(),
premiseProviderId: $('#PremiseProviderId').val()
};
$("body").load(url, data);
};
Here is a code snippet from the Bootstrap 3 official Site on how to implement the button state feedback:
<script>
$('#loading-example-btn').click(function () {
var btn = $(this)
btn.button('loading')
$.ajax(...).always(function () {
btn.button('reset')
});
});
</script>
My Question is how can I implement in my GenerateBill script, the bootstrap example uses an Ajax call, can I make it work without making too many changes to what I have?
If I might make a few suggestions that will both fix your issue and improve your code.
Instead of using an onclick event, add an event listener in your javascript, and call the function from there.
Add the .button('loading') call to that same event listener.
Don't leave off the href for an <a> tag. It will cause some browsers to not show the pointer correctly on hover.
Your link will look as follows:
Generate Bill
Leaving your GenerateBill() logic alone, the listener you need to add to your javascript:
$('#loading-example-btn').click(function () {
$(this).button('loading');
GenerateBill();
});
A working example of this code (with GenerateBill() simplified) is available here: http://www.bootply.com/VTSNA1XMcm

Categories