Reputation: 20637
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
Upvotes: 1
Views: 5327
Reputation: 41832
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.
Upvotes: 3
Reputation: 30073
Use onclick or onchange event:
select.onclick = function () {
select.options[0].selected = true;
}
Upvotes: 4
Reputation: 30394
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.
Upvotes: 5
Reputation: 70414
Try something like this (jQuery):
$('select[name^=options]').change(function () {
$(this).children(':first').attr('selected', true);
});
Upvotes: 5