Alejandro Maliachi Quintana Alejandro Maliachi Quintana - 5 months ago 11
Javascript Question

Trouble with click function on custom plugin

Im trying to create a plugin (not a good work but just want to learn) and im having trouble with adding a clic event.

Here is the plugin:

(function($) {

$.fn.selectMe = function() {

return this.filter(".selectMe").each(function() {

var sel = $(this);
var listOpt = "";

/* Hide the <select> tag and create a new element ".selectMe" */
sel.css("display","none");
var selName = sel.attr("name");
sel.after("<div id='"+selName+"' class='selectMe'><div class='selLabel'><span></span><i class='fa fa-lg fa-angle-down pull-right'></i></div><div class='selOptions'></div></div>");

/* Look for <option> of his parent and add them to the new element*/
sel.find("option").each(function() {
var optVal = $(this).val();
var optText = $(this).text();
/*listOpt += "{"+optVal+"} ";*/
listOpt += "<li data-value='"+optVal+"'>"+optText+"</li>";
});
$("#"+selName+" .selOptions").html("<ul>"+listOpt+"</ul>");

});

};

}( jQuery ));


And here is the HTML code:

<select class="selectMe" name="cars">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Fiat</option>
<option value="4">Audi</option>
</select>
<select class="selectMe" name="options">
<option value="1">Opt 1</option>
<option value="2">Opt 2</option>
<option value="3">Opt 3</option>
<option value="4">Opt 4</option>
</select>


In wich part of the jquery plugin i must write the event and how?
How can i prevent double interations?

Answer

Right after you append the new list can use find('li').click(fn)

$("#"+selName+" .selOptions")
       .html("<ul>"+listOpt+"</ul>") /// your code ends here
       .find('li')
       .click(function(){
             var $li = $(this).addClass('selected');
             $li.siblings().removeClass('selected');
             sel.val( $li.data('value') ); // set value of select
        });

I would suggest you use some sort of prefix for your ID to avoid collisions with other items in the page.

Also, you shouldn't need filter(".selectMe") as you would likely call the plugin using:

$(".selectMe").selectMe()