jQuery getting data attribute not working - javascript

I have a script that produces a number of buttons with a class and I want it to alert the data attribute on click but it's not working.
Here is the output of HTML
<button class="request box-button" data-value="18492500814">Request</button>
jQuery code
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).data('value'));
});
});
});

Since your elements don't exist when the page loads, the event won't be bound to them. Fix that by using event delegation:
$(document).ready(function(){
$(document).on('click','.request', function () {
alert($(this).data('value'));
});
});
JS Fiddle demo with dynamically generated elements
Note: Here, I used $(document).on() because I don't have your page's structure. But if you insert the buttons in a container that already exists in your HTML, use this instead: $('#myContainer').on(). It won't be noticeable, but it is best for performance.

Why not just have the listener on request, instead of inside of the loop. Also use the attr to get the data-value
$(document).ready(function(){
$('.request').click(function () {
alert($(this).attr('data-value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>

Try with attr method.
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).attr('data-value'));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>

Related

How to call a function when a div is dynamically generated using jQuery

The scenario I want to achieve is as follow:
$("#parentDiv").on("load",'#childDiv', function () {
// do something...
});
I would like to call a function when a child div is dynamically generated and shown on the page, but there is no suitable event that can achieve this. Any hint or help would be appreciated.
Instead of load, you can make use of a custom event which gets triggered with .trigger():
$(document).ready(function() {
$("button").on("click", function() {
$("body").append("<div id='new'>Created</div>").trigger('custom-event');
});
});
$(document).on("custom-event", function() {
console.log('DIV created!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Create element</button>
</body>

button click jquery not working

Should be a really simple answer but I can't figure it out right now. I have this button:
<button id="logout" type="button">Logout</button>
And it's supposed to run this jQuery code within script tags at the bottom of the body:
$("#logout").addEventListener("click", function () {
alert('Button Clicked');
});
However, no alert pops up. I don't get it. Thanks in advance.
addEventListener is a method of DOM element not of jQuery object which is an array-like structure that contains all the selected DOM elements
To attach event using jQuery, use .on => Attach an event handler function for one or more events to the selected elements
Try this:
$("#logout").on("click", function() {
alert('Button Clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="logout" type="button">Logout</button>
Using JS:
document.getElementById("logout").addEventListener("click", function() {
alert('Button Clicked');
});
<button id="logout" type="button">Logout</button>
Edit: You can get first DOM element from array-like object returned by jQuery selector using $(SELECTOR)[0] or $(SELECTOR).get(0)
addEventListener() method registers the specified listener on the EventTarget.
If you really want to use addEventListener then write the following code:
var el = document.getElementById("logout");
el.addEventListener("click", function () {
alert('Button Clicked');
}, false);
Otherwise do it with jquery
$(document).on("click", "#logout", function () {
alert('Button Clicked');
});
OR
$("#logout").on("click", function () {
alert('Button Clicked');
});
Alternate answer is:
$(document).on("click", "#logout", function() {
alert('Button Clicked');
});
This works on dynamically created elements as well.
You should use on method to use the event handlers in jquery. The addEventListener is a core JavaScript event method.
$("#logout").on("click", function() {
alert('Button Clicked');
});
You may still use addEventListner forcing jQuery code to JavaScript:
$("#logout")[0] //Now, this is JavaScript Object
.addEventListener("click", function () {
alert('Button Clicked');
});
You can use jQuery click/on function for getting the button to work.
Example:
$("#logout").on("click", function () { alert('Button Clicked'); });
$("#logout").click(function () { alert('Button Clicked'); });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#logout").on("click", function () {
alert('Button Clicked');
});
});
</script>
</head>
<body>
<button id="logout" type="button">Logout</button>
</body>
</html>
If you go to your console like in firebug and type $() you will see the jQuery object that shows the methods and properties of the jquery function/object. There is no addEventListener on this object.
addEventlistener is a method for the DOM. If you want to take advantage of jQuery by "writing less and do more" use jQuery methods like on. This will allow you to add an event handler on an element.
$(document).on("click", "#logout", function() {
alert('button clicked');
});
var element = document.getElementById("logout");
element.addEventListener("click", myFunction);
function myFunction() {
// your code logic comes here
}

button action after insert with jquery not working

i have an button "add" i click it then a save button will append to my div. this is working, but i cant trigger the function of the "save" button. if i paste the "save"- button in the code directly it is working. i cant find my error...
<a class="save" href="#"><img src="images/save.png" alt="save_working" /></a>
<a class="add_row" href="#"><img src="images/icon_add_light.png" alt="add" /></a><br>
<div id="hinzu"></div>
$(".save").click(function() {
alert("saveworking");
});
$(".add_row").click(function() {
$("#hinzu").append(' <a class="save" href="#"><img src="images/save.png" alt="savenotworking" /></a>');
});
Here is an fiddle with it: http://jsfiddle.net/MgcDU/321/
Why isnt this working with the js append method?
It's dynamic, so it does not exist when you're binding the event. For that you would need to delegate the event to an element that actually exists at the time of attaching the event handler :
$("#hinzu").on('click', '.save', function() {
alert("saveworking");
});
Use it like:
$("#hinzu").on('click', ".save", function() {
alert("saveworking");
});
this is because when you try to do the $(".save") it does not exist.
You have to use the on() for monitoring if any new .save are in your doom and assign the event handler.
$("#hinzu").on('click', '.save', function()
{
alert("This Does work");
});
It is not working because the $(".save").click() call binds the onclick handler to all elements with class save which already existed at the point of the call.
To bind the event handler also to elements which did not exist at the time of the binding, you must use $(document).on('click', '.save', function() { [...] })
If you want to save you code, use this:
<script type="text/javascript">
$(function() {
$('.save').click(function() {
alert('saveworking');
});
});
$(function() {
$('.add_row').click(function() {
alert('add_row');
});
});
</script>
One more way to do this:
<script type="text/javascript">
$(document).ready(function () {
$('.save').click(function () {
alert('saveworking');
});
$('.add_row').click(function () {
alert('add_row');
});
});
</script>

HTML content is not getting on Jquery click function

In my code I have the following:
$(document).ready(function(){
$("input#Addmore").click(function(){
$('div#add_div').append("<a class='remove' href='#'>X</a>");
});
});
This code on click of add more button and I want to remove parent div of above added code on click of "X" by jquery. for that purpose i am using this code
$("a.remove").click(function(){
$(this).closest("div").remove();
});
But the code is not working because jQuery did not getting append anchor code. Can any one tell me the solution?
You need to delegate the event to the nearest static element. Try this:
$('#add_div').on('click', 'a.remove', function() {
$(this).closest("div").remove();
});
Or if you are using an older version of jQuery (less than 1.7) use delegate() like this:
$('#add_div').delegate('a.remove', 'click', function() {
$(this).closest("div").remove();
});
Try this
$('#add_div').delegate('a.remove', 'click', function() {
$(this).closest("div").remove();
});
Or you can try this:
$("input#Addmore").click(function(){
$("div#add_div").append("<a class='remove' href='javascipt:;' onclick='remove(this);return false' href='#'>X<br/></a>");
});
and here is remove function:
window.remove = function(obj)
{
$(obj).closest('div').remove();
}
see here : http://jsfiddle.net/Hvx2u/3/

Hooking events with .on() with JQUERY

I want to hook events with the .on() method. The problem is I don't know how to get the object reference of the element on which the event take place. Maybe it's a midunderstanding of how the method really works... but I hope you can help.
Here's what I want to do:
When a file is selected, I want the path to be displayed in a div
<div class="wrapper">
<input type="file" class="finput" />
<div class="fpath">No file!</div>
</div>
Here's my script
$(document).ready(function() {
$this = $(this);
$this.on("change", ".finput", {}, function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Something like that but that way it doesn't work.
Like this
$(document).ready(function() {
$('.finput').on("change", function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Do you need to use on()? I'm not sure what you are trying to do exactly.
$("#wrapper").on("change", ".finput", function(event){
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
I haven't tested your code, but you need to attach the on() to the wrapper.
Can you just use change()?
$('.finput').change(function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
This should help. If you want to see when a file input changes, bind the event to it
$("input[type='file']").on("change", function(e){
var path = $(this).val();
})
Try:
$(document).ready(function() {
$('body').on('change','input.finput', function() {
var path = $(this).val()
$(this).parent().children(".fpath").html(path.split("\\").pop());
});
});
$(document).on("change", ".finput", function() {
$(".fpath").html(this.value.split("\\").pop());
});
This is a delegated event handler, meaning the .finput element has been inserted dynamically so we need to delegate the listening to a parent element.
If the .finput element is not inserted with Ajax and is present on page load, you should use something like this instead:
$(".finput").on("change", function() {
$(".fpath").html(this.value.split("\\").pop());
});

Categories