user1234
user1234

Reputation: 3159

How to make first option a default value in dropdown using Jquery-Chosen plugin

I have a dropdown whose value I need to default to a first value available in the dropdown option.

Js:

$('#chosen').find('ul.active').find('li.child') // will return me an array of options.
   [
     <li class="child" data-option-array-index="1">Abs</li>
     <li class="child" data-option-array-index="2">Abg</li>
     <li class="child" data-option-array-index="3">Abk</li>
   ]

I tried to default it to the first value by doing:

 $('#chosen').find('ul.active').find('li.child').attr('data-option-array-index').prop('selected', true);

But this returns an error. I'm not sure how to select a value for default when the dropdown options are a result of array. Any ideas?

Upvotes: 2

Views: 4843

Answers (2)

talemyn
talemyn

Reputation: 7950

From the looks of your code, my guess is that you are using a plugin or library that creates stylized "dropdowns", using HTML lists (i.e., <ul> and <li> tags), styled with CSS to make it look like a dropdown.

The problem that you are facing is that the selected property is specific to the <select> element, so trying to add it to an <li> is likely why you are seeing an error.

Now, not knowing what plugin/library that you are using, I can tell you that, in order to make sure that the selection made in the "fake" dropdown is still passed to the server when it is submitted, these dropdowns are usually tied to a hidden <select> behind-the-scenes, using some form of JavaScript, and there is also usually a method in the API that allows you to manually auto-select the value that you want to.

Assuming that I am right about using an external plugin/library, I'd take a look at the documentation for more information on how to set a default selection.


Based on your comment that you are using the jQuery Chosen plugin, and, after looking at the options page on the Chosen website ( http://harvesthq.github.io/chosen/options.html ), it looks like you should simply be able to place the selected property in the <option> value that the plugin is applied to and it will automatically select the value in the generated dropdown.

selected, disabled - Chosen automatically highlights selected options and disables disabled options.

If you need to add the selected property AFTER the plugin has been applied, you would use JS/jQuery to add the property to the <option> that you want selected and then refresh the Chosen dropdown with this:

$('#YOUR_SELECT_ELEMENT').trigger('chosen:updated');

Upvotes: 1

Eric
Eric

Reputation: 487

Try this:

$('#chosen').find('ul.active').find('li.child')[0].prop('selected', true);

You get the first element in the array of options returned. Then you set its property "selected" to true.

Upvotes: 0

Related Questions