jQuery get parent id not working - javascript

I'm not great with JavaScript/jQuery and am having a lot of trouble with a very basic task. I have an img that, when clicked, should give me the id of the parent div it is within.
This is the markup:
<div id="client-1">
<img src="~/Content/plus.ico" alt="plus" onclick="ButtonExpandClick()" />
</div>
And here is the javascript:
<script type="text/javascript">
function ButtonExpandClick() {
alert($(this).parent().attr("id"));
}
</script>
Clicking the image gives me an alert that says "undefined" but I can clearly see that the div has the id of "client-1" when I inspect the page. I must be missing something simple here. I've also tried using .closest as well as passing this into the function but no luck. Thanks for any help!

Don't use the onclick attribute for events. You're using jQuery, bind the events "properly".
Add a class to the image(s):
<img src="~/Content/plus.ico" alt="plus" class="icon" />
Then bind the event:
$(function(){
$('.icon').click(function(){
alert($(this).parent().attr("id"));
});
});

If you hook up the click event using jQuery instead of doing it inline, then you'll get the this passed in automatically:
Note that you'd have to give the image an id or find another selector for it.
jQuery(document).ready(function() {
jQuery("#myImg").click(ButtonExpandClick);
});

You need to pass in this
onclick="ButtonExpandClick(this)"
JS
function ButtonExpandClick(elem) {
alert($(elem).parent().attr("id"));
}
Also it is a bad idea to declare inline events . Attach the event directly using javascript.
<script>
$(function() {
$('#client-1 img').click(function() {
alert($(this).parent().attr("id"));
});
});
</script>

You have to use jquery.click or send your element with function. like sendme(this).

Simpler still you might try this with a binding:
<div id="client-1">
<img src="~/Content/plus.ico" alt="plus" />
</div>
<script>
$(function() {
$('img').on('click', function(){
// Two ways to do the same thing
alert(this.parentNode.id);
alert($(this).parent()[0].id);
});
});
</script>

You can use something like this:
$(function() {
$('img').on('click', function(e) {
var id = this.parentNode.id; //Using javascript to access id is faster.
alert(id);
});
});
Example working at Jsfiddle
It's recommended put this images inside a container. and change this to. It's better for performance.
$(function() {
var images = $('#container').find('img');
images.on('click', function(e) {
var id = this.parentNode.id; //Using javascript to access id is faster.
alert(id);
});
});

Related

Get custom css property with a function

This is my code :
<html>
<body>
<button class="myclass" data-card-id="1">Save</button>
</body>
</html>
My question is how whould look like a function that when user click on any of "myclass" buttons submit a variable with data-card-id of the specific card in a php file.
Thank you ! :)
this is using Jquery:
$(".myclass").click(function(){
$(this).attr( "data-card-id" );
});
JSFIDDLE - http://jsfiddle.net/q5j8z/11/
see browser console for data display
// change the selector "ul li a" to your button
$('ul li a').click(function (e) {
e.preventDefault();
var value = $(this).data('value');
$('.button').data('value', value);
console.log($('.button').data('value'));
});
$('.button').click(function (e) {
e.preventDefault();
console.log($(this).data('value'));
});
This can be accomplished through an additional selection feature. I believe "data-card-id" is an attribute of your html tag, so you have two choices.
Bind the click to the element using the selector or delegate it to the body of the document, I think you'll see how either way works here.
Option 1. The advantage here is that when click events bubble up to the body this will check and execut appropriately, even if other buttons are added to the page after this code is executed. This is jquery's click delegation feature
$('body').on('click', 'button[data-card-id="1"]', function(){
//perform your action
});
Option 2. This binds the click event to the object itself. This can be more straight forward and has its advantage in simplicity.
$('button[data-card-id="1"]').click(function(){
// perform some action
});
And of course you have a plethora of other approoaches......
or
$('button').each(function(){
if($(this).attr("data-card-id") == '1'){
$(this).click(function(){
//some action
});
}
});
There are other approaches, too. Let me know if none of these seem to work.
JS FIDDLE DEMO
The most simpler would be to use this code -- >
just change this card-id to this cardid
HTML
<button class="myclass" data-cardid="1">Save</button>
<button class="myclass" data-cardid="2">Save</button>
JS
$(document).ready(function(){
$(".myclass").on('click',function(){
var cid = $(this).data("cardid");
alert(cid);
});
});

.click function not working when the event is called by element created by another function

I have this function that create an element
function AddPayment(ID)
{
showForm = $('#AddPaymentForm').html();
$('#divAJAX_'+ID).html(showForm);
$(".cancel").click(function(){ AddPayment(ID); });
}
Coming from this
<div id='AddPaymentForm'>
<span class='button' id='cancel' class='cancel' >Cancel</span>
</div>
I wanted that function to place the element in here
<div id='divAJAX_ID'></div>
I also wanted that function to create an onclick function on my span, but it isn't working.
I guess the problem is coming from placing the
$(".cancel").click(function(){ AddPayment(ID); });
at the wrong placement. I've tried all the possible place but I can't still work this right.
What's wrong?
You have two class attributes on the same element. It should be something like:
class="button cancel"
instead of
class="button" id="whatever" class="cancel"
It is probably causing trouble to jQuery.
See how it start working on this fiddle: http://jsfiddle.net/pvNrg/2/
First, your question as the html:
<div id='AddPaymentForm'>
<p>Coming from this</p>
</div>
<span id='cancel' class='cancel'>Cancel</span>
<p>I wanted that function to place the element in here</p>
<div id='divAJAX_ID'></div>
<p>I also wanted that function to create an onclick function on my span, but it isn't working. I guess the problem is coming from placing the ... at the wrong placement. I've tried all the possible place but I can't still work this right.</p>
<p>What's wrong?</p>
And the javascript:
$(function () {
function AddPayment(ID) {
showForm = $('#AddPaymentForm').html();
$('#divAJAX_' + ID).html(showForm);
}
$(".cancel").click(function () {
AddPayment('ID');
});
});
For dynamically created elements ,You have to do event delegation
$(document).on("click", ".cancel" , function(event){
alert($(this).text());
});
Use this code
function AddPayment(ID)
{
var showForm = $('#AddPaymentForm').html();
var container = $('#divAJAX_'+ID);
container.html(showForm);
container.find(".cancel").click(function(){ AddPayment(ID); });
}
$("#AddPaymentForm,[id^=divAJAX_]").on("click", ".cancel" , function(event){
alert($(this).text());
});
Attach the delegated event handlers only the list of containers you need to monitor (not the document) if you need to save performance (you don't need to monitor all the .cancel). With this approach, the event does not have to bubble up more levels. If you have anther element that is parent of AddPaymentForm and all divAJAX_. You could write like this:
$("#anotherContainer").on("click", ".cancel" , function(event){
alert($(this).text());
});

Access dynamically created items using jQuery?

I have a page where some html is being dynamically added to the page.
This is the html and javascript that is created:
<div>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
<a id="btn">Button</a>
</div>
Looking in my Firebug console, I get an error that says:
TypeError: $("#btn") is null
jQuery is being loaded on the page initially.
What am I doing wrong here?
You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.
Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.
Assuming that you're loading the $('#btn') into the #container div (for example), to give:
<div id="container">
<div>
Button text
</div>
</div>
Then use:
$('#container').on('click', '#btn', function(){
alert('Button clicked!');
});
Use .on to wire up the event to your button. Check this SO answer:
Event binding on dynamically created elements?
$(document).ready(function() {
$('body').on('click', '#btn', function() {
alert("Hello");
});
})
Edit: I added the document ready code, you'll want to make sure you do that.
Fixed.
you are looking for .on here which will bind the click event to dynamically added nodes.
$("#parent_container").on("click", "#btn", function () {
alert("hello")
})
the docs: http://api.jquery.com/on/
Try
<div>
<a id="btn">Button</a>
</div>
<script>
$('#btn').on('click', function() {
alert("Hello");
});
</script>
The problem in your code is that you are attaching the event to the button before the button is being created.
Correct version is:
<div>
<a id="btn">Button</a>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
</div>
This should do the job.
Use the .live() function of jQuery

Jquery Javascript - Make inline js a function

Ok so this i probably very easy but i can't seem to figure it out. I have a a function but i still have to call the function inline. I am wondering if there is a way to put it all in the function. Right now my function looks like this:
function ddItem(el) {
$(el).closest(".ddSelectHeader").find("input").attr({
value : $(el).text()
})
}
Then i call this function inline like this:
<div class="ddContainer">
<div class="ddSelectHeader"><input name="" type="text" />
<div class="ddSubmenu">
Item 1<br />
item 2
</div>
</div>
Ok so i am trying to make a simple drop down but with divs instead of the traditional ul li. The way it is written above works fine but i was hoping there is a way to take the onlcick out so that any link that is click within the ddSubmenu will populate the input field. This way i don't have to call it inline or in the html.
Thanks for the help.
$(document).ready(function() {
$(".ddSubmenu a").click(function(){
var $this = $(this);
$this.closest(".ddSelectHeader").find("input").val($this.text());
});
})
$(function(){
$('.ddSubmenu > a').click(function(){
var self = $(this);
self.closest(".ddSelectHeader").find("input").val(self.text());
});
});
Via javascript, you can use element.onclick: https://developer.mozilla.org/en/DOM/element.onclick
or jQuery's .click(): http://api.jquery.com/click/
$('.ddSubmenu a').click(function(){
ddItem(this);
});

how do we change onclick function via .attr() in jquery?

i got this url
<a class="remove_item' rel="4" onclick="javascript:jQuery(#blablabla)" href="javascript:;' >remove</a>
i'm using this simple find and replace
item.find('a.remove_class').attr({
title:'hello',
click:'hello();'
} );
but it seem it's not working. i still not able to replace javascript:jQuery(#blablabla) with another function.
To set onClick you should use something like this $("a").attr("onclick", js);
where js is a string containing your javascript code.
Try attaching the event handler using the below code snippet in your page body:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.remove_item').click(hello);
});
</script>
jQuery has no built-in way to assign event handlers in that way. Use the DOM0 method to set the onclick handler instead:
item.find('a.remove_class').each(function() {
this.onclick = function() {
alert("Clicked!");
};
});
Also, don't put javascript: in you event handler attributes. It's incorrect and only works by coincidence.
Why not just do this.
<script type="text/javascript">
$(document).ready(function() {
$("a.remove_item").click(function() {
alert("You have clicked my <a>!!");
//do other stuff
});
});
</script>
The attr doesn't recognises the onclick attribute, get the html element (.get(0)) and use "raw" functions to extract the onclick attribute.
On Firefox the following works:
$("element").get(0).getAttribute("onclick")
You can remove by using
$("element").get(0).removeAttribute("onclick")
or setting a empty string
$("element").get(0).setAttribute("onclick", "")

Categories

Resources