views:

228

answers:

4

Hey,

I have a select options form fields setup like below:

<select name="options[]" multiple="multiple">
  <option value="1" selected="selected">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>

The user can select multiple options, but I would like the first option to be selected and always remain selected. The user should not be able to unselect the first option, basically making it mandatory field.

Is it possible to do this? I don't mind using JavaScript or Jquery to achieve this, I have tried making the option "selected" and "disabled" but the user can still unselect the first option.

Cheers

Eef

+4  A: 

Try something like this (jQuery):

$('select[name^=options]').change(function () {
    $(this).children(':first').attr('selected', true);
});
RaYell
+3  A: 

You will have to (re)select the option every time a selection is made. I'd use the onchange() handler. It may be better to rework the UI a bit to show users that it's not really optional. And make sure the backend doesn't depend on that option being selected, in case js is off or buggy.

Scott Saunders
+1 for mentioning to rework the UI.
rahul
I have taken this into consideration and went with the reworking of the UI, will improve the 'User Experience' in the long run. Thanks
Eef
+1  A: 

Use onclick or onchange event:

select.onclick = function () {
    select.options[0].selected = true;
}
Anatoliy
+1 : the easier the better.
enguerran
+2  A: 

As others have mentioned, you have the (re)select the option every time they change it. But another important thing to note is that whatever this form is being used for (such as server side data processing) needs to know this rule to. Otherwise, all someone has to do is go to your site, disable javascript, and then choose an option you don't want them to have.

Matt