Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add title attribute to Chosen option tags?

I'm using "Chosen plugin" and not sure how to add an attribute to the option tags of the select list.

I have tried this using jQuery on document ready but no luck.

like image 706
NKD Avatar asked Sep 19 '25 22:09

NKD


2 Answers

you need to modify the Chosen.Jquery.js to the following to make it work

Using Chosen 1.0 version

Line no 62 add this line of code

this.parsed.push({
        array_index: this.parsed.length,
        options_index: this.options_index,
        value: option.value,
        text: option.text,
        html: option.innerHTML,
    title: option.title, // this is Line 62 add this line
        selected: option.selected,
        disabled: group_disabled === true ? group_disabled : option.disabled,
        group_array_index: group_position,
        classes: option.className,
        style: option.style.cssText
      });

Modify Line No 255

return "<li title=\"" + option.title +"\"  class=\"" + (classes.join(' ')) + "\"" + style + " data-option-array-index=\"" + option.array_index + "\">" + option.search_text + "</li>";
like image 83
Vidhyasagar SS Avatar answered Sep 23 '25 10:09

Vidhyasagar SS


I have tried this..but no luck

That depends what you tried. Give this function a go, calling it with the select element that you want its chosen counterpart to inherit titles

function cloneTitles(selectBox) {
    //make sure it has already been chosen-ised
    selectBox = $(selectBox).chosen();

    //get all the original options, should be in same order as chosen ones
    var origOpts = selectBox.find('option');

    //get all the chosen-created 'options'
    //NB there may be a better way to grab the chosen created element
    var chznOpts = selectBox.next().find('.active-result')

    //foreach option
    origOpts.each(function(index, origOpt) {
        //copy the attribute from the original
        $(chznOpts[index]).attr('title', $(origOpt).attr('title'));
    });
}

I have tried this on document ready
Your problem may have been that you were doing whatever you tried before chosen.js had converted your select boxes, but this function should mitigate that.

Also, if you need this for multiple select boxes, just use .each()
(E.g. selectArray.each(function(i, select) { cloneTitles(select); })

I assume you're using jQuery and not Prototype (given your last line)
So you could pass in '#id' instead of <DOMObj> if you wanted.
Code could be modified to clone a given attribute, instead of 'title', or even an array of given attributes!

like image 27
Hashbrown Avatar answered Sep 23 '25 12:09

Hashbrown