简体   繁体   中英

Make select2 boxes wide enough for contents

I have this table in jsfiddle . I want the name column to be wide enough to fit the names available in the options without truncation.

I have explored the suggestions in the Select2 appearance documentation , but those don't seem to provide what I'm seeking.

If possible, I would like it to automatically shrink or widen to fit the longest available text in the data .

在此处输入图片说明

<table>
<tr><td>name</td><td>sex</td><td>age</td></tr>
<tr><td><select class="name" multiple="multiple"><option></option></select><td><input name="sex"/></td><td><input name=
"age"/></td></tr>
<tr><td><select class="name"/><td><input name="sex"/></td><td><input name=
"age"/></td></tr>
</table>

<script>
var options = [
  {id: 1, text: 'Alexander Allen Abrahms III'},
  {id: 2, text: 'Benjamin Barry Bautista Jr.'}
]



$(".name").select2({data:options, placeholder: 'Full name'});
</script>

You can use css and define style on select tag like this:

<select class="name" style="width:100%" multiple="multiple">
   <option></option>
</select>

and define table cell width:

<table>
   <thead>
     <tr>
       <th width=50%> Name </th>
       <th width=25%> Sex </th>
       <th width=20%> Age </th> 
    </tr>
   </thead>
   <tbody> Your table body</tbody>
</table>

Here is yours edited code in fiddle https://jsfiddle.net/3hrdrjj4/1/

EDIT:

Fiddle with select width responsive to picked options and fixed placeholder https://jsfiddle.net/3hrdrjj4/5/

if i didn't get it wrong u want this right?

you can just simply add style="width: 250px;" to the inputs you desire. or add width: 250px; to the name class.

https://jsfiddle.net/wLzxo9ba/5/

The other way to resolve it is:

<table style="width:100%">
    <tr>
        <td style="width:50%">name</td>
        <td style="width:15%">sex</td>
        <td style="width:15%">age</td>
    </tr>
    <tr>
        <td style="width:50%"><select class="name" multiple="multiple" style="width:100%"><option></option></select>
        <td style="width:15%"><input name="sex"/></td>
        <td style="width:15%"><input name="age"/></td>
    </tr>
    <tr>
        <td style="width:50%"><select class="name"  style="width:100%"/>
        <td style="width:15%"><input name="sex"/></td>
        <td style="width:15%"><input name="age"/></td>
    </tr>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM