Cannot select ID with Jquery from $.get() / $.load() function. Please Help Me? - javascript

My Javascript something like this
$('button').click(function(){
//load the data and place inside to #content
});
$('#id-from-data-that-load').click(function(){
//Do some action
});
So this is html tag
<button>Load</button>
<div id="content">
//Empty Data
</div>
when button LOAD clicked html will be like this
<button>Load</button>
<div id="content">
<div id="id-from-data-that-load">
content that load
</div>
</div>
BUT, when i clicked div id-from-data-load the function won't run.
How to solve it?

You need to use live for the div event instead. Here's what it should be:
$('#id-from-data-that-load').live("click", function(){
//Do some action
});
Or alternatively you could also do this:
var submitted = false;
$('button').click(function(){
// If the button was clicked before, we don't submit again.
if (submitted == true) { return false; }
// Set submitted to true, so when user clicks the button again,
// this operation will not be processed one more time.
submitted = true;
//load the data and place inside to #content
$.post("/getdata", {}, function(response) {
//after the load happened we will insert the data into the div.
$("#content").html(response);
// Do the bindings here.
$('#id-from-data-that-load').click(function(){
//Do some action
});
});
return false;
});

try:
$('#id-from-data-that-load').live("click", function() {
alert($(this).attr("id");
});

you need to bind events to elements loaded at runtime through either the .live handler or .delegate handler. That is because when you are binding events to elements they are not present on the dom. So .live and .delegate would help you achieve that. See example from #shree's answer

Bind id-from-data-that-load after data load in content.
$('button').click(function(){
//load the data and place inside to #content
$('#id-from-data-that-load').click(function(){
//Do some action
});
});

When you bind the LIs you can hardcode the function name into the onclick attribute.
<li onclick="myFunction">Blah Blah Blah</li>

Related

prevent from window.location to child div Jquery

I'm currently working with this code, anytime I click on the div it goes to the url...
HTML
<div class='gotoPost' data-href='post?i=24'>[text]</div>
JQUERY
$(function() {
toUrl = function(){
var GoToUrl = $(this).data('href');
var redirect = GoToUrl;
window.location = redirect;
}
});
$(function() {$(".gotoPost").on('click',toUrl);});
PROBLEM
Now I want to add a absolute-positioned div at the top of the container, but anytime I click on it. (to show a Lightbox) it goes to the url...how do I prevent it from going to the url? I want when clicked the child div,it doesnt go to the url.
<div class='gotoPost' data-href='post?i=24'>[text]
<div class=ShowLightBox>3</div>
</div>
So Your question is..
<div class='gotoPost' data-href='post?i=24'>
[text]
<div class=ShowLightBox>3</div>
</div>
If you click 'showlightbox' div, it doesn't redirect to other page,
but when you click other area of 'gotoPost', then you want to redirect page. right?
Solution
So here's the solution:
$(function() {
toUrl = function(e){
if (e.target.classList.contains('gotoPost')) {
var GoToUrl = $(this).data('href');
var redirect = GoToUrl;
window.location = redirect;
}
}
});
$(function() {$(".gotoPost").on('click', toUrl);});
If you use call-back function with JS, when event happends it will call call-back function with 'EVENT' object, which contains 'e.target' - HTML Element you've click.
the code above check if your click event is targeting 'gotoPost' directly not inside HTML element. So this would work for you! :)
ps. Checkout "Event Delegation with JavaScript".
You need to prevent the click event on .ShowLightBox from propagating. For example:
$('.ShowLightBox').on('click', function(e){
e.stopPropagation();
// Open light box
});
Ref: https://api.jquery.com/event.stoppropagation/

jquery/ajax - .load keeping the same JQuery

Basically,
What I'm trying to do is have a button which when you click, loads up another .html form
which has a button to the next .html page and so on and so on..
The first part works, and, for the form to be loaded, however, when the next form is loaded the jquery does not work for the button.. For example:
index1.html:
<button id="LoadForm" value="form1.html">Load the form</button>
$(document).ready(function() {
function foo(x) {
$('.content').load(x);
}
$('#LoadForm').click(function() {
var ele = $(this).attr("value");
$(this).hide();
form(ele);
});
});
In form1.html:
<button id="LoadForm" value="index.html">Go to form2..</button>
Where am I going wrong here?
1) You can't have duplicate ids on the same page, so .content must contain the original #LoadForm button (I assume it does) and
2) you need to use a delegated event handler for dynamically added elements:
$(document).ready(function() {
function foo(x) {
$('.content').load(x);
}
$(document).on('click', '#LoadForm', function() {
var ele = $(this).attr("value");
$(this).hide();
form(ele); // This should be foo in your example :)
});
});
This works by listening for click events bubbling up to a non-changing ancestor (document is the best default of there is nothing closer. Never use 'body' as it has problems related to styling). It then applies the jQuery filter. It then applies the supplied function for any selected elements that generated the event.
and 3) you have foo and form in your example. Please correct the code :)

jQuery selector click function clarification

Theres a gap in my understanding that i'd liked filled;
I have a basic jQuery click function like this..
$('.cl').each(function(e)
{
alert('works');
$(this).click(function()
{
alert('no works');
});
});
My HTML is like this:
<body>
<div id='c0'>
<div class='bO cl'>Button</div>
</div>
</body>
Basic stuff.
The 'works' alert is fired ok - but with the click function nothing happens - 'no works' is not fired.
Also
$('.cl').click(function()
{
alert('help');
});
Does not work. Simple stuff i'm sure but i'm missing something.
Why is this?
One thing to make sure is that you run the event handler once the DOM and jQuery are initialized, which is by doing this:
$(function() {
$('.cl').click(function()
{
alert('help');
});
});
Also alternatively, if your cl is loaded after the fact such as by an Ajax call you can alternativley do this
$("body").on("click", ".cl", function() {
// Your code here
})
This registers the click event with the body but only gets dispatched if the actual target is of type cl.

A click function not working

my a click jquery function is not working, it just doesn't give any errors at console at all too.
Here is the link -
Edit
and here is the click function
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
It doesn't popout the alert box, nor it does show me error in console.
Okay, someone asked for more info -
The link is added with jquery, by pressing button, and as id it takes one of the input fields value and inserts it as link with id from input field. There are no duplicate ids, all javascript scripts are located at the end of head tag, and the a click function is located last in part.
Based on your edit that the <a> tag is being inserted dynamically, you'll need to use jQuery's .on() (jQuery version 1.7 and later) or .live() method to attach the click handler.
This code should work, so I suppose there is some other error before this code runs that prevents correct Javascript execution.
Edit: OR the DOM is not yet ready when you insert the Javascript code. Then you should use
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});​
});
Are you wrapping it on the ready event or after the element has been displayed? If so then it should work;
http://jsfiddle.net/sWeRf/
Either place this code after the Edit on the page, or put it in the head with $(document).ready(function() { //Place code here. });
Can you try replacing your JS code with the following (put between the HEAD tags)
<script type="text/javascript">
$(document).ready(function(){
$('a#lang').click(function(){
alert($(this).attr('id'));
});
});
</script>
Are you checking the document is loaded before applying your JQuery click handler?
e.g.
$(document).ready(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
Instead of using document.ready you can use an anonymous function that does the same thing.
Like this:
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
To remove the item do this:
$('#language_c').remove();

Append an onClick event to an anchor tag using jquery?

I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});

Categories