Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set selected options via JS #4

Open
dror-nahmias opened this issue Sep 28, 2011 · 0 comments
Open

Set selected options via JS #4

dror-nahmias opened this issue Sep 28, 2011 · 0 comments

Comments

@dror-nahmias
Copy link

I was looking for a way to set selected options using JS.
I came up with the following:

/**
* Set selected options with the given values
*
* @param arrValues
* The value of the item(s) being selected
*/
    this.selectOptions = function (arrValues) {
        // give options correct attributes

        $selectSingle.find('option').each(function () {
            var currVal = $(this).attr('value');
            if ($.inArray(currVal, arrValues) > -1) {   
                $(this).attr({selected: 'selected', 'disabled' : 'disabled'}).data('disabled', 1);
            } else {
                $(this).removeAttr('selected').removeAttr('disabled').removeData('disabled');
            }
        });
        //empty list of selected
        $list.empty();
        // add the new selected options
        // this did not work with selected!!!
        $selectSingle.find(':disabled').each(function () {
            add($(this), null, false);
        });
    };

Don't know if it is the best way but it works.
I feel it's wrong to play around with the actual data and attributes (rather call on a function for this)
Also selecting by the selected attribute failed but was OK using the disabled attribute - weird...

Be happy to get your corrections/thoughts on this.

Thank you for creating this plugin!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant