0

Initially when I had static elements (same class but different ids) all over my webpage, below was the jquery I was using, which worked correctly.

<script>
$(document).ready(function () {
    $('.swipe').each(function () {
        var pdid=$(this).attr('id');
        //create a closure variable instead of a global one
        var Slider = $(this).Swipe({
            continuous: false,
            stopPropagation: true,
            callback: function (index, elem) {
            lid=index+1;
            },
        }).data('Swipe');

        //use relative tranversal to find the next/prev elements
        $(this).next().next('.next').click(function (data) {
            Slider.next();
            $("#fimg_"+pdid).val($("#"+pdid+"_"+lid).data('src'));
            // alert($("#"+pdid+"_"+lid).data('src'));

        });

        //try using $.proxy
        $(this).next('.prev').click(function(data) {
            $.proxy(Slider.prev());
            $("#fimg_"+pdid).val($("#"+pdid+"_"+lid).data('src'));
        });
    });


    $(".approveid").click(function(){
        var adid=$(this).attr('id').slice(8);
        alert(adid);
        $("#share_rss_form_"+adid).submit();

    });


     $(".category").change(function() {

        // Get the value of the option that was chosen
        // You could also do: var currentValue = this.options[this.selectedIndex].value;
        var currentValue = $(this).val();
        var cid=$(this).attr('id').slice(9);
        // Don't do anything if the "Please select" option was chosen
        if (currentValue == '0') {
          return;
        }

        // Load some data from the server into the next <div>

        $.get('../abc_options.php?cat='+currentValue, function( data ) {
            $("#selectTags"+cid).prepend(data);
            $("#selectTags"+cid).trigger('liszt:updated');
        });

      });


    $('.selectTags').chosen();
    // $('#selectTags1').trigger('chosen:updated');

    $('.share_rss_form').each(function(index,e1){
        $(e1).validate({
            errorClass: "error",
            validClass: "success",
            highlight:function(element, errorClass, validClass) {
                $(element).parent().addClass(errorClass).removeClass(validClass);
             },
            unhighlight:function(element, errorClass, validClass) {
                $(element).parent().addClass(validClass).removeClass(errorClass);
             },
            submitHandler: function(form) { 
                alert(form.id)      ;
                $(form).ajaxSubmit();
                // return true;

            }
        });

    });

    $('.loadNext').click(function(){
        window.location.replace("abc"+$(this).attr('id')+".htm"); 

    });

});

</script>

However, I now need to generate those static HTML elements dynamically on the fly. It would be like using a .post to a url and fetching the entire content on click of a button. The above jquery doesn't seem to be binding to the dynamically created elements.

While I am looking into the options of jquery .live and .on, I am not sure of how to convert the above code to bind to my dynamic elements at runtime. As I comprehend, .on works for some events like "Click", but if you see the jquery code above, I dont have click events for everyone (eg: swipe,selectTags,shareRSSForm).

Could someone please help in showing me how to convert the above code to bind to dynamically created elements at run time?

UPDATED ISSUE: I have Next button coded as below

 $('.loadNext').on('click',function(){
         $('#loadNextVal').val(parseInt($('#loadNextVal').val())+parseInt(1));

            $("#share_rss_form_load").load("RSSFeeds/abc3.htm #share_rss_form_"+$('#loadNextVal').val());

            //alert(1)
 runMyCode($("#share_rss_form_load").load("RSSFeeds/abc3.htm #share_rss_form_"+$('#loadNextVal').val()));


    });

and the HTML code is Next

When I click the next button the dynamic content is loaded but the jquery doesnt bind to it immediately, when I click the Next button again to load the next element, for a fraction of few seconds, the jquery gets binded to the previous dynamically created element before changing to the next dynamic elemnt. It looks like a problem of late binding or binding too early before the element exists because if I place a alert box in between (as seen above), it works correctly

Please help

UDATED: my runMycode function

function runMyCode(parent){ 
    $('.swipe',$(parent)).each(function () {
        var pdid=$(this).attr('id');
        //create a closure variable instead of a global one
        var Slider = $(this).Swipe({
            continuous: false,
            stopPropagation: true,
            callback: function (index, elem) {
            lid=index+1;
            },
        }).data('Swipe');

        //use relative tranversal to find the next/prev elements
        $(this).next().next('.next').click(function (data) {
            Slider.next();
            $("#fimg_"+pdid).val($("#"+pdid+"_"+lid).data('src'));
            // alert($("#"+pdid+"_"+lid).data('src'));

        });

        //try using $.proxy
        $(this).next('.prev').click(function(data) {
            $.proxy(Slider.prev());
            $("#fimg_"+pdid).val($("#"+pdid+"_"+lid).data('src'));
        });
    });





    $('.selectTags',$(parent)).chosen();
    // $('#selectTags1').trigger('chosen:updated');

    $('.share_rss_form',$(parent)).each(function(index,e1){
        $(e1).validate({
            errorClass: "error",
            validClass: "success",
            highlight:function(element, errorClass, validClass) {
                $(element).parent().addClass(errorClass).removeClass(validClass);
             },
            unhighlight:function(element, errorClass, validClass) {
                $(element).parent().addClass(validClass).removeClass(errorClass);
             },
            submitHandler: function(form) { 
                alert(form.id)      ;
                $(form).ajaxSubmit({ 
                    success: function(data) { 
                        alert(data);
                    } 
                });
                // return true;

            }
        });

    });

}

Sunny D'Souza
  • 616
  • 5
  • 11
  • 27
  • @HashemQolami My question is basically for those elements that arent triggered by "Click" event, how do you bind those? – Sunny D'Souza Feb 22 '14 at 05:22
  • As the accepted answer has suggested, you could pass the *eventName* as the first parameter to `.on()` method. Whether it is `click` event or anything else. – Hashem Qolami Feb 22 '14 at 05:26
  • the code seems to be fine what error do you get in console log? – Exlord Feb 23 '14 at 08:07
  • there was a issue with $('.selectTags',$(parent)).chosen(); which I commented out, now I dont get any error but it seems runMyCode() doesnt bind the jquery to the elements :( – Sunny D'Souza Feb 23 '14 at 08:15

2 Answers2

1

you can use like this

    $("body").on("click",".approveid",function(){
       var adid=$(this).attr('id').slice(8);
       alert(adid);
       $("#share_rss_form_"+adid).submit();
    });
  • Thanks Fahim, but certain events arent triggered on click, thats my question...example..check the .swipe class, how do i make it dynamic? – Sunny D'Souza Feb 22 '14 at 05:21
0

I had the exact same problem with adding jquery ui buttons to ajax loaded content. this is what i did :

make a function to run your code :

function runMyCode(parent){ 
    $('.swipe',$(parent)).each(...);
}

then in your ajax/post success callback :

success:function(data){
  //data is what you have loaded from server
  runMyCode(data);
}

UPDATED:for the new problem

$('.loadNext').on('click', function () {
    var loadNextVal = parseInt($('#loadNextVal').val());
    $('#loadNextVal').val(loadNextVal + parseInt(1));

    $.load("RSSFeeds/abc3.htm #share_rss_form_" + loadNextVal,function(data){
        runMyCode(data);
        ("#share_rss_form_load").html(data);
    });
});

UPDATED:see if there is a error

$("#share_rss_form_load").load("RSSFeeds/abc3.htm #share_rss_form_" + loadNextVal,
    function (response, status, xhr) {
        if (status == "error") {
            console.log(xhr.status + " " + xhr.statusText);
        } else
            runMyCode(response);
    });
Exlord
  • 5,009
  • 4
  • 31
  • 51
  • Thanks Exlord, is it necessary to pass on the parent as argument? Actually I need the code to run when I click a "Next" button and not on form submit. Also, initially when the document loads I need to bind the jquery, what would I pass on as parent then? – Sunny D'Souza Feb 23 '14 at 04:50
  • yes the parent is required other wise you will have duplicate event handlers attached to the objects . pass the document object on page load runMyCode(document); – Exlord Feb 23 '14 at 05:22
  • Thanks Exlord, but the problem is the binding seems to be doing late...please check my updated problem above.. – Sunny D'Souza Feb 23 '14 at 05:41
  • thanks for the solution, firebug shows an error - : $.load is not a function :( – Sunny D'Souza Feb 23 '14 at 07:22
  • actually, even if a reframe to $("#share_rss_form_load").load("RSSFeeds/abc3.htm #share_rss_form_" + $('#loadNextVal').val(),function(data){ runMyCode(data); }); the script seems to fail – Sunny D'Souza Feb 23 '14 at 07:45
  • you could check my updated runMyCode, in case if there are any errors in it – Sunny D'Souza Feb 23 '14 at 07:56
  • yes, firebug console shows "TypeError: this.search_field[0] is undefined"..which points to jquery chosen plugin...even commenting that out, I cant see the runMycode jQuery bind to any element :( – Sunny D'Souza Feb 23 '14 at 08:10