Solved

Jquery selectable function for elements load by ajax

Posted on 2015-02-17
7
61 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
7 Comments
 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 40614795
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
ID: 40614816
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
ID: 40614945
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
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 
LVL 2

Assisted Solution

by:Panos
Panos earned 0 total points
ID: 40615038
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 43

Expert Comment

by:Rob
ID: 41596476
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 43

Expert Comment

by:Rob
ID: 41596477
Objecting to handle misallocation of points
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Bootstrap Form 16 42
2 separate CSS animations 2 32
javascript and jquery question 4 26
Keyup listener getting fired on initial page load 1 16
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…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
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…

726 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