Solved

Jquery selectable function for elements load by ajax

Posted on 2015-02-17
7
35 Views
Last Modified: 2016-05-21
Hello experts
I need help with my code.
I'm using jquery 1.7.1 and jquery ui 1.8.18
I have a list where using the selectable function i'm calling a function with selected like:
(...selected: function(event, ui) {.....)
The problem i have is that it is not working for elements that not exist jet in DOM
My code:
<ul class="ui-selectable">
<li id ="partid_0" class="partselect ui-selectee">All</li>
<li id ="partid_1" class="partselect ui-selectee">test 1</li>
<li id ="partid_2" class="partselect ui-selectee">test 2</li>
</ul>


<script type="text/javascript">
$(".ui-selectable").selectable({
    selected: function(event, ui) {
        var target = ui.selected.id;
        var i = target.split("_");
        var optval = parseInt(i[1]);
        var curul = $(this);
        $.ajax({
            type: "post",
            url: "myurl",
            data: {
                getsub: optval,
                returnformat: "json"
            },
            success: function(d) {
                var df = $.parseJSON(d);
                var opt = df[0]['options'];
                $("<ul  class='ui-selectable' id='part_" + optval + "'></ul>").insertAfter(curul);
                var output = [];
                $.each(opt, function(index, value) {
                    output.push('<li id ="partid_' + value.categoryid + '" class="partselect ui-selectee">' + value.categoryname + '</li>');
                });
                $('#part_' + optval).html(output.join(''));

            }
        }, "json")
    }
});  
</script>

For the created list this function is not working.
Any help with?
0
Comment
Question by:Panos
  • 3
  • 2
7 Comments
 
LVL 44

Expert Comment

by:Rainer Jeschor
Comment Utility
Hi,
before diggin into the code, I think you have a logical issue here.
You have the initla UL with the initial LI elements, having IDs partid_x
Then after your ajax call you create the UL with the exact same id and you add the UL directly inside the existing UL/LI structure.
At least the doubled id entries will mess up everything in the DOM.
And second question:
do you really want to bind the exact same functionality to the newly created elements? Because then you will have an "endless" tree down (assuming that the ajax call returns something).
Thanks.
Rainer
0
 
LVL 2

Author Comment

by:Panos
Comment Utility
Hi Rainer Jeschor
Thank you for your post. I did post here a test code deleteting all unneccessary code  making it simple as possible and i did not noticed the id issues. (i use for ul part_.....ids and for li partid_...ids. I don't think that there will be two elements with the same id. The created list elements use unique id's from DB.
I think that the .insertAfter(curul); will add the new ul after the existing one and not inside of it (or not?)
0
 
LVL 2

Accepted Solution

by:
Panos earned 0 total points
Comment Utility
I found a solution but i think there would be a better way sending the selected: function(event, ui) to a function.
My solution is as follow:
$(".ui-selectable").selectable({
    selected: function(event, ui) {
        var target = ui.selected.id;
        var i = target.split("_");
        var optval = parseInt(i[1]);
        var curul = $(this);
        $.ajax({
            type: "post",
            url: "myurl",
            data: {
                getsub: optval,
                returnformat: "json"
            },
            success: function(d) {
                var df = $.parseJSON(d);
                var opt = df[0]['options'];
                $("<ul  class='ui-selectable' id='part_" + optval + "'></ul>").insertAfter(curul);
                var output = [];
                $.each(opt, function(index, value) {
                    output.push('<li id ="partid_' + value.categoryid + '" class="partselect ui-selectee">' + value.categoryname + '</li>');
                });
                $('#part_' + optval).html(output.join(''));
                $(".ui-selectable").selectable({
    selected: function(event, ui) {
        var target = ui.selected.id;
        var i = target.split("_");
        var optval = parseInt(i[1]);
        var curul = $(this);
        $.ajax({
            type: "post",
            url: "myurl",
            data: {
                getsub: optval,
                returnformat: "json"
            },
            success: function(d) {
                var df = $.parseJSON(d);
                var opt = df[0]['options'];
                $("<ul  class='ui-selectable' id='part_" + optval + "'></ul>").insertAfter(curul);
                var output = [];
                $.each(opt, function(index, value) {
                    output.push('<li id ="partid_' + value.categoryid + '" class="partselect ui-selectee">' + value.categoryname + '</li>');
                });
                $('#part_' + optval).html(output.join(''));

            }
        }, "json")
    }
});  
            }
        }, "json")
    }
});  

Open in new window


I'm copying pasting the whole code after the created new list
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 2

Assisted Solution

by:Panos
Panos earned 0 total points
Comment Utility
A second way is to use the on click function with body and than use a custom code to customize the appearing of the selected li element
 $("body").on("click", ".partselect", function (e)  {
        e.preventDefault();
          $(this).parent().children().removeClass('ui-selected');
        $(this).addClass('ui-selected');
..........
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 500 points for panosms's comment [url="https://www.experts-exchange.com/questions/28618633/Jquery-selectable-function-for-elements-load-by-ajax.html#a40614945"]#a40614945[/url]
Assisted answer: 0 points for panosms's comment [url="https://www.experts-exchange.com/questions/28618633/Jquery-selectable-function-for-elements-load-by-ajax.html#a40615038"]#a40615038[/url]

for the following reason:

No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Split:
-- Panos (http:#a40614945)
-- Panos (http:#a40615038)


If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

tagit
Experts-Exchange Cleanup Volunteer
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
Objecting to handle misallocation of points
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now