<SELECT multiple> - how to allow only one it

2020-05-11 07:28发布

I have a <SELECT multiple> field with multiple options and I want to allow it to have only one option selected at the same time but user can hold CTRL key and select more items at once.

Is there any way how to do it? (I don't want to remove 'multiple').

8条回答
Animai°情兽
2楼-- · 2020-05-11 07:46

Why don't you want to remove the multiple attribute? The entire purpose of that attribute is to specify to the browser that multiple values may be selected from the given select element. If only a single value should be selected, remove the attribute and the browser will know to allow only a single selection.

Use the tools you have, that's what they're for.

查看更多
地球回转人心会变
3楼-- · 2020-05-11 07:47

If the user should select only one option at once, just remove the "multiple" - make a normal select:

  <select name="mySelect" size="3">
     <option>Foo</option>
     <option>Bar</option>
     <option>Foo Bar</option>
     <option>Bar Foo</option>
  </select>

Fiddle

查看更多
做个烂人
4楼-- · 2020-05-11 07:48

I am coming here after searching google and change thing at my-end.

So I just change this sample and it will work with jquery at run-time.

$('select[name*="homepage_select"]').removeAttr('multiple')

http://jsfiddle.net/ajayendra2707/ejkxgy1p/5/

查看更多
▲ chillily
5楼-- · 2020-05-11 07:49

Just don't make it a select multiple, but set a size to it, such as:

  <select name="user" id="userID" size="3">
    <option>John</option>
    <option>Paul</option>
    <option>Ringo</option>
    <option>George</option>
  </select>

Working example: https://jsfiddle.net/q2vo8nge/

查看更多
Bombasti
6楼-- · 2020-05-11 07:51
<select name="flowers" size="5" style="height:200px">
 <option value="1">Rose</option>
 <option value="2">Tulip</option>
</select>

This simple solution allows to obtain visually a list of options, but to be able to select only one.

查看更多
我命由我不由天
7楼-- · 2020-05-11 07:52

You want only one option by default, but the user can select multiple options by pressing the CTRL key. This is (already) exactly how the SELECT multiple is meant to behave.

See this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple

Can you please clarify your question?

查看更多
登录 后发表回答