0

I created a simple script with jqueryui-selectable list. I generate a selectable list and assign each list with an onclick function. It seems that the onclick event was not triggered when I clicked the list. Any idea to solve this problem?

Thanks,

my script:

$(document).ready(function() {
$("#myButton").button();
});

function generate(){
var $content=$("<ol id='selectable'>");
for (a=0;a<3;a++)
{
$content.append("<li class='ui-widget-content'  onclick='myFunction()'>item"+a+"</li>");
}
$content.append("</ol>");
$("#myList").append($content);
$('#selectable').selectable();
}

function myFunction()
{
alert("Hello World!");
}

my style:

#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable  .ui-selected { background: #F39814; color: white; }
#selectable  { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable  li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }

my html:

<div id='myList'/>
<button id="myButton" onClick="generate()">Generate List</button>

3 Answers3

1

Since the element is dynamically created, it needs to be delegated. You can do this in jQuery by:

$(document).on("click",".ui-widget-content", myFunction()); 

(Or just use an anonymous function)

$(document).on("click",".ui-widget-content", function() {
    alert("Hello World!");
}); 
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
1

You should use selecting event. See example here http://jsfiddle.net/Pa4NK/

Yaroslav Osetrov
  • 894
  • 1
  • 10
  • 13
  • I have another problem. Actually I want to pass the variable 'a' value from the list generation to myFunction. For instance myFunction will look like this : function myFunction(msgNo) { alert(msgNo); } is it possible to do it? – Alvinadi Wijaya Dec 13 '13 at 09:21
  • This is the right option. You have the selecting and unselecting event for example (http://api.jqueryui.com/selectable/) – André Aug 06 '15 at 09:29
0

The selectable adds a helper div to display the lasso. But the helper div is positioned under the mouse, which prevents the click from hitting the underlying element. Even though the helpers width and height are set to 0, this seems to cause the problems.

Change the distance option will solve the issue http://api.jqueryui.com/selectable/#option-distance

$( "#selectable" ).selectable({
 distance: 1
});

& Then implement what the selectable() function does

    $('.ui-widget-content').on("click", function () {
        $('.ui-widget-content').removeClass('ui-selected');
        $(this).addClass('ui-selected');
    });
SaadK
  • 1,507
  • 20
  • 33