jQuery Select2: How to add placeholder text for multi-value selectboxes - javascript

I'm working with multi-value selectboxes using the Select2 jQuery plugin. These text boxes have tagging enabled, so the user can enter arbitrary values. I have a placeholder set using the select2 options, but it is only visible when the selectbox is empty. See below.
Empty selectbox, shows placeholder:
Selectbox has values, no placeholder:
What I'd like to have is something like the image below. I'd like to specify a different placeholder value for the search input field that will show only when the selectbox has values in it. When the selectbox is empty, the placeholder will return to the initial placeholder value.

On the event change.select2 you can check if there are more than 0 values selected and so you can reset the placeholder to a new value:
$('.js-example-basic-multiple').on('change.select2', function (e) {
if ($('.js-example-basic-multiple').val().length > 0) {
$('.js-example-basic-multiple').data('select2')['$container'].find(':input[type=search]')
.attr({placeholder: "Select a state again and again", style: 'width: 100%;'})
}
});
The snippet:
$('.js-example-basic-multiple').select2({
placeholder: "First selection....",
allowClear: false
});
$('.js-example-basic-multiple').on('change.select2', function (e) {
if ($('.js-example-basic-multiple').val().length > 0) {
$('.js-example-basic-multiple').data('select2')['$container'].find(':input[type=search]')
.attr({placeholder: "Select a state again and again", style: 'width: 100%;'})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select class="js-example-basic-multiple js-states form-control select2-hidden-accessible" multiple=""
data-select2-id="select2-data-61-g4nr" tabindex="-1" aria-hidden="true" style="width: 100%;">
<optgroup label="Alaskan/Hawaiian Time Zone" data-select2-id="select2-data-66-rote">
<option value="AK" data-select2-id="select2-data-67-tgfy">Alaska</option>
<option value="HI" data-select2-id="select2-data-68-1ncw">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone" data-select2-id="select2-data-69-ey9b">
<option value="CA" data-select2-id="select2-data-70-cjom">California</option>
<option value="NV" data-select2-id="select2-data-71-qoj8">Nevada</option>
<option value="OR" data-select2-id="select2-data-72-q7yi">Oregon</option>
<option value="WA" data-select2-id="select2-data-73-ph4j">Washington</option>
</optgroup>
<optgroup label="Mountain Time Zone" data-select2-id="select2-data-74-wzgi">
<option value="AZ" data-select2-id="select2-data-75-86ql">Arizona</option>
<option value="CO" data-select2-id="select2-data-76-3mqr">Colorado</option>
<option value="ID" data-select2-id="select2-data-77-ry7y">Idaho</option>
<option value="MT" data-select2-id="select2-data-78-z7m6">Montana</option>
<option value="NE" data-select2-id="select2-data-79-2lte">Nebraska</option>
<option value="NM" data-select2-id="select2-data-80-xd5z">New Mexico</option>
<option value="ND" data-select2-id="select2-data-81-2wmh">North Dakota</option>
<option value="UT" data-select2-id="select2-data-82-0lmr">Utah</option>
<option value="WY" data-select2-id="select2-data-83-yeoz">Wyoming</option>
</optgroup>
<optgroup label="Central Time Zone" data-select2-id="select2-data-84-mr5y">
<option value="AL" data-select2-id="select2-data-85-l6br">Alabama</option>
<option value="AR" data-select2-id="select2-data-86-jpai">Arkansas</option>
<option value="IL" data-select2-id="select2-data-87-x0o2">Illinois</option>
<option value="IA" data-select2-id="select2-data-88-k0y3">Iowa</option>
<option value="KS" data-select2-id="select2-data-89-oki5">Kansas</option>
<option value="KY" data-select2-id="select2-data-90-ot5d">Kentucky</option>
<option value="LA" data-select2-id="select2-data-91-j93e">Louisiana</option>
<option value="MN" data-select2-id="select2-data-92-ljou">Minnesota</option>
<option value="MS" data-select2-id="select2-data-93-4cwz">Mississippi</option>
<option value="MO" data-select2-id="select2-data-94-4452">Missouri</option>
<option value="OK" data-select2-id="select2-data-95-hee9">Oklahoma</option>
<option value="SD" data-select2-id="select2-data-96-h9gh">South Dakota</option>
<option value="TX" data-select2-id="select2-data-97-q4kh">Texas</option>
<option value="TN" data-select2-id="select2-data-98-wps1">Tennessee</option>
<option value="WI" data-select2-id="select2-data-99-mdzk">Wisconsin</option>
</optgroup>
<optgroup label="Eastern Time Zone" data-select2-id="select2-data-100-iqi4">
<option value="CT" data-select2-id="select2-data-101-rkjk">Connecticut</option>
<option value="DE" data-select2-id="select2-data-102-ih1a">Delaware</option>
<option value="FL" data-select2-id="select2-data-103-4zkz">Florida</option>
<option value="GA" data-select2-id="select2-data-104-sdgj">Georgia</option>
<option value="IN" data-select2-id="select2-data-105-ulm1">Indiana</option>
<option value="ME" data-select2-id="select2-data-106-onok">Maine</option>
<option value="MD" data-select2-id="select2-data-107-qwwa">Maryland</option>
<option value="MA" data-select2-id="select2-data-108-j2v5">Massachusetts</option>
<option value="MI" data-select2-id="select2-data-109-uhro">Michigan</option>
<option value="NH" data-select2-id="select2-data-110-ui5e">New Hampshire</option>
<option value="NJ" data-select2-id="select2-data-111-yd0u">New Jersey</option>
<option value="NY" data-select2-id="select2-data-112-h33j">New York</option>
<option value="NC" data-select2-id="select2-data-113-7t3i">North Carolina</option>
<option value="OH" data-select2-id="select2-data-114-bc13">Ohio</option>
<option value="PA" data-select2-id="select2-data-115-lbm3">Pennsylvania</option>
<option value="RI" data-select2-id="select2-data-116-zgza">Rhode Island</option>
<option value="SC" data-select2-id="select2-data-117-kyou">South Carolina</option>
<option value="VT" data-select2-id="select2-data-118-npxe">Vermont</option>
<option value="VA" data-select2-id="select2-data-119-2ony">Virginia</option>
<option value="WV" data-select2-id="select2-data-120-xyi2">West Virginia</option>
</optgroup>
</select>

Related

jQuery Validation show error message for only one specific select field (bootstrap-select)

I am using bootstrap-select plugin along with jQuery Validation plug in and am adding some custom error states to the select dropdowns (red border). I almost have everything working as I would like. The one issue I cannot seem to figure out is how to display error text along with the custom error border I created on ONE of the input fields. I added an addMethod to the form validation which is checking for a min age of 18 which is working but the Error message needs to show along with the custom red border I have created when they select an age that does not meet the requirements of the addMethod (must be 18)
https://codepen.io/mDDDD/pen/qBZWpbj
html:
<div class="custom-select-box">
<select class="selectpicker select-input multiple select-month" name="dobMonth"
id="selectMonth">
<option selected="true" disabled="disabled">Month</option>
<option value="January">January</option>
<option value="Febuary">Febuary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<div class="dropdown-caret-div">
<i class="fal fa-angle-up"></i>
<i class="fal fa-angle-down"></i>
</div>
</div>
<div class="custom-select-box">
<select class="selectpicker select-input multiple select-day" name="dobDay" id="selectDay">
<option selected="true" disabled="disabled">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<div class="dropdown-caret-div">
<i class="fal fa-angle-up"></i>
<i class="fal fa-angle-down"></i>
</div>
</div>
<div class="custom-select-box">
<select class="selectpicker select-input multiple select-year" name="dobYear" id="selectYear">
<option selected="true" disabled="disabled">Year</option>
<option value="2020">2020</option>
<option value="2019">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
<option value="1975">1975</option>
<option value="1974">1974</option>
<option value="1973">1973</option>
<option value="1972">1972</option>
<option value="1971">1971</option>
<option value="1970">1970</option>
<option value="1969">1969</option>
<option value="1968">1968</option>
<option value="1967">1967</option>
<option value="1966">1966</option>
<option value="1965">1965</option>
<option value="1964">1964</option>
<option value="1963">1963</option>
<option value="1962">1962</option>
<option value="1961">1961</option>
<option value="1960">1960</option>
<option value="1959">1959</option>
<option value="1958">1958</option>
<option value="1957">1957</option>
<option value="1956">1956</option>
<option value="1955">1955</option>
<option value="1954">1954</option>
<option value="1953">1953</option>
<option value="1952">1952</option>
<option value="1951">1951</option>
<option value="1950">1950</option>
<option value="1949">1949</option>
<option value="1948">1948</option>
<option value="1947">1947</option>
<option value="1946">1946</option>
<option value="1945">1945</option>
<option value="1944">1944</option>
<option value="1943">1943</option>
<option value="1942">1942</option>
<option value="1941">1941</option>
<option value="1940">1940</option>
<option value="1939">1939</option>
<option value="1938">1938</option>
<option value="1937">1937</option>
<option value="1936">1936</option>
<option value="1935">1935</option>
<option value="1934">1934</option>
<option value="1933">1933</option>
<option value="1932">1932</option>
<option value="1931">1931</option>
<option value="1930">1930</option>
</select>
<div class="dropdown-caret-div">
<i class="fal fa-angle-up"></i>
<i class="fal fa-angle-down"></i>
</div>
</div>
</div>
<!-- select box row-->
jQuery:
$userInfoForm.validate({
debug: true,
ignore: [],
rules: {
userIs: {
required: true,
},
dobMonth: {
required: true,
},
dobDay: {
required: true,
},
dobYear: {
minAge18: true,
minAge10: false,
required: true,
},
},
messages: {
userIs: 'This field is required.',
dobMonth: 'Date of birth is required.',
dobDay: 'Month is required.',
dobYear: {
minAge18:
'We're sorry but you need to be at least 18 years old to register.',
required: 'Year is required.',
},
},
errorPlacement: function (error, element) {
if ($(element).is('select')) {
$(element).parent('div').addClass('dropdown-has-error');
} else if ($(element).attr('name') === 'userIs') {
$(element).siblings('label.select-role').addClass('radio-has-error');
} else {
element.attr('placeholder', error.text());
}
},
success: function (label, element) {
$(element).parent('div').removeClass('dropdown-has-error');
$(element).siblings('label.select-role').removeClass('radio-has-error');
}
$('.selectpicker').on('change', function () {
$(this).valid();
if ($(this).hasClass('error')) {
$(this).parent('div').addClass('dropdown-has-error');
} else {
$(this).parent('div').removeClass('dropdown-has-error');
}
});
//add validator method - user must be at least 18 years of age
$.validator.addMethod(
'minAge18',
function (value, element) {
var yearToday = new Date().getFullYear();
value = parseInt(value, 10);
return yearToday - value >= 18;
},
'Update minAge18 error message in validator'
);
css:
.error {
color: red;
}
.radio-has-error::before {
border: 2px solid red;
}
.dropdown-has-error {
border: 2px solid red !important;
}
You don't have error messages because you've eliminated them from the errorPlacement function.
errorPlacement: function (error, element) {
if ($(element).is('select')) {
$(element).parent('div').addClass('dropdown-has-error');
} else if ($(element).attr('name') === 'userIs') {
$(element).siblings('label.select-role').addClass('radio-has-error');
} else {
element.attr('placeholder', error.text());
}
},
Any select is going to hit the first conditional, which only adds a class.
if ($(element).is('select')) {
$(element).parent('div').addClass('dropdown-has-error');
The default errorPlacement function contains something like the following, which you've neglected to include anywhere...
error.insertAfter(element);
You have a element.attr('placeholder', error.text()), which will simply change the placeholder attribute into the error message, but only when the other conditionals fail. I don't think using the placeholder for error messages is proper GUI since that's not what a placeholder is supposed to be... and AFAIK, there is no placeholder on select elements.
So if you're missing messages, it's because you've overwritten the default errorPlacement without inserting the error object anywhere into your DOM.
That being said, you should not be using errorPlacement for adding classes. You should only use it for placing the message into your layout. Once placed, the plugin toggles the message. If you add classes here, then you would need to remove them somehow, which is what you're doing with the success callback. However, this all just isn't quite right.
errorPlacement is for placing the message into the layout.
success is for leveraging the message itself when the element is valid, such as placing a green checkmark.
If you want to add and remove classes, then use the highlight and unhighlight callback functions as that's exactly what these are here to do.

Selecting value return wrong value

I have Select in my View
Here is code
<li class="airline">
<select name="search[airline]" id="search_airline" class="custom" style="display: none;">
<option value="">Alla</option>
<option value="SK">SAS</option>
<option value="DY">Norwegian</option>
<option value="EI">Aer Lingus</option>
<option value="SU">Aeroflot</option>
<option value="AR">Aerolineas Argentinas</option>
<option value="AM">Aeromexico</option>
<option value="BT">Air Baltic</option>
<option value="AC">Air Canada</option>
<option value="CA">Air China</option>
<option value="UX">Air Europa</option>
<option value="AF">Air France</option>
<option value="AI">Air India</option>
<option value="NZ">Air New Zealand</option>
<option value="AZ">Alitalia</option>
<option value="NH">All Nippon Airways</option>
<option value="AA">American Airlines</option>
<option value="OS">Austrian Airlines</option>
<option value="VO">Austrian Arrows</option>
<option value="BA">British Airways</option>
<option value="BD">British Midland</option>
<option value="SN">Brussels Airlines</option>
<option value="CX">Cathay Pacific</option>
<option value="CO">Continental Airlines</option>
<option value="OK">Czech Airlines</option>
<option value="DL">Delta Airlines</option>
<option value="EK">Emirates</option>
<option value="EY">Etihad Airways</option>
<option value="AY">Finnair</option>
<option value="GA">Garuda Indonesia</option>
<option value="IB">Iberia</option>
<option value="FI">Icelandair</option>
<option value="KL">KLM</option>
<option value="KE">Korean Air Lines</option>
<option value="LA">LAN Airlines</option>
<option value="LO">LOT - Polish Airlines</option>
<option value="NG">Lauda Air</option>
<option value="LH">Lufthansa</option>
<option value="DM">Maersk Air</option>
<option value="MH">Malaysian Airlines</option>
<option value="TF">Malmö Aviation</option>
<option value="MX">Mexicana Airlines</option>
<option value="NW">Northwest Airlines</option>
<option value="DY">Norwegian</option>
<option value="OA">Olympic Airways</option>
<option value="QF">Qantas Airways</option>
<option value="QR">Qatar Airways</option>
<option value="SK">SAS</option>
<option value="SQ">Singapore Airlines</option>
<option value="SA">South African Airways</option>
<option value="LX">Swiss Intl Air Lines</option>
<option value="TP">TAP Portugal</option>
<option value="TG">Thai Airways</option>
<option value="TK">Turkish Airlines</option>
<option value="UA">United Airlines</option>
<option value="VS">Virgin Atlantic Airw.</option>
<option value="VY">Vueling</option>
<option value="WF">Wideroe</option>
</select>
<span tabindex="0" id="search_airline-button" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-owns="search_airline-menu" aria-haspopup="true" class="ui-selectmenu-button ui-selectmenu-button-closed ui-corner-all ui-button ui-widget"><span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span>
<span class="ui-selectmenu-text">Flygbolag: Alla</span>
</span>
</li>
Also I have function in TS that make variable in it with word - "Flygbolag"
Here is it
function update_search_airline() {
$(".ui-selectmenu-text", $("#search_airline-button")).html(
__("Flygbolag") + ": " + $(".ui-selectmenu-text", $("#search_airline-button")).html());
}
So when I load page all okay and I get for example
But when I select value from this select I need to make it with this word too
So in function I make this code
function load_field_actions(): void {
$(".tooltip").tooltipster()
$("#search_airline").change(update_search_airline)
}
And this row must update it correctly
$("#search_airline").change(update_search_airline)
But it just change default value to next value without Flygbolag

change select option by javascript

i have problem in javascript
i make carwebsite
i need to achieve functionality as per the image
when I choose company in "make" select box,
it shows me all classes. Then I need to choose a "class" from second dropdown and it should show me all Models
now i get one code
<script type="text/javascript">
$(document).ready(function(){
$('.car').change(function()
{ getcar = $(this).val();
//console.log(getcar);
$('.subcar').hide();
$('.'+getcar).show();
}); });
// end DOM
</script>
this is select (make)
<select name="car" class="car">
<option value="0" SELECTED="SELECTED">--Choose--</option>
<option value="Acura">Acura</option>
<option value="Alfa_Romeo">Alfa Romeo</option>
<option value="Aston_Martin">Aston Martin</option>
<option value="Audi">Audi</option>
<option value="Bentley">Bentley</option>
<option value="BMW">BMW</option>
<option value="Buick">Buick</option>
<option value="Cadillac">Cadillac</option>
<option value="Can_Am">Can Am</option>
<option value="Chery">Chery</option>
<option value="Chevrolet">Chevrolet</option>
<option value="Chrysler">Chrysler</option>
<option value="Citroen">Citroen</option>
<option value="Daihatsu">Daihatsu</option>
<option value="Dodge">Dodge</option>
<option value="Ducati">Ducati</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
<option value="Ford">Ford</option>
<option value="GMC">GMC</option>
</select>
this is select (class)
<select name="branch_name" class="subcar Acura" style="display:none;">
<option value="0" SELECTED="SELECTED" DISABLED="DISABLED">- None -</option>
<option value="CL">CL</option>
<option value="CSX">CSX</option>
<option value="EL">EL</option>
<option value="ILX">ILX</option>
<option value="ZDX">ZDX</option></select>
<select name="branch_name" class="subcar Alfa_Romeo" style="display:none;">
<option value="0" SELECTED="SELECTED" DISABLED="DISABLED">- None -</option>
<option value="101">101</option>
<option value="156">156</option>
<option value="156CROSSWAGON">156CROSSWAGON</option>
<option value="Spider">Spider</option>
</select>
<select name="branch_name" class="subcar Aston_Martin" style="display:none;">
<option value="0" SELECTED="SELECTED" DISABLED="DISABLED">- None -</option>
<option value="DB9">DB9</option>
<option value="Healey">Healey</option>
<option value="Vantage">Vantage</option>
</select>
how can i make third select
???

How to make select appear one after one in JS?

I am new in JS and I need some help. I want my 2-nd selectto appear only if the first one is already chosen, the 3-th select to appear after the second choise is done and the submit button to appear after the third choise is done.Is it possible to do that using a loop ?
<style>
select{float:left}
#month,#day,input{display:none}
</style>
<select required id='year' class='selectOption' onchange='select(this)'>
<option value=""> Select year</option>
<option value="">2016</option>
<option value="">2015</option>
<option value="">2014</option>
<option value="">2013</option>
<option value="">2012</option>
<option value="">2011</option>
<option value="">2010</option>
<option value="">2009</option>
<option value="">2008</option>
<option value="">2007</option>
</select>
<select required id='month' class='selectOption' onchange='select(this)'>
<option value=""> Select month</option>
<option value="">January</option>
<option value="">February</option>
<option value="">March</option>
<option value="">April</option>
<option value="">May</option>
<option value="">June</option>
<option value="">July</option>
<option value="">August</option>
<option value="">September</option>
<option value="">October</option>
<option value="">November</option>
<option value="">December</option>
</select>
<select required id='day' class='selectOption' onchange='select(this)'>
<option value="">Select Day</option>
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
<option value="">5</option>
<option value="">6</option>
<option value="">7</option>
<option value="">8</option>
<option value="">9</option>
<option value="">10</option>
<option value="">11</option>
<option value="">12</option>
<option value="">13</option>
<option value="">14</option>
<option value="">15</option>
<option value="">16</option>
<option value="">17</option>
<option value="">18</option>
<option value="">19</option>
<option value="">20</option>
<option value="">21</option>
<option value="">22</option>
<option value="">23</option>
<option value="">24</option>
<option value="">25</option>
<option value="">26</option>
<option value="">27</option>
<option value="">28</option>
<option value="">29</option>
<option value="">30</option>
<option value="">31</option>
</select>
<input type="submit" class='selectOption'>
</form>
function select(par) {
var i = 0;
var x = document.getElementsByClassName('selectOption');
if (par.selectedIndex !== "0" && i<x.length) {
x[i++].style.display = 'block';
}
}
</script>
you can achieve this by hiding all select but the first one on page load and displaying them one by one after selecting the previous select.
<select required id='month' class='selectOption hide' onchange='select(this)'>
<select required id='day' class='selectOption hide' onchange='select(this)'>
plunker : http://plnkr.co/edit/oKwq0q4IB5poKuUOa6oG?p=preview
Define your function like this.
function select(par) {
if (par.selectedIndex !== 0) {
par.nextElementSibling.className = "selectOption";
}
}

Get or Set Value(s) on A Multi-select Form Field

When you have a multi-select form field such as the following, how do you get, and set the selected option values?
<select class="items" multiple="multiple" size="5">
<option value="apple">apple</option>
<option value="ant">ant</option>
<option value="ape">ape</option>
<option value="age">age</option>
<option value="boy">boy</option>
<option value="banana">banana</option>
<option value="carrot">carrot</option>
</select>
Getting the value(s)
var items = [];
$('select.items option:selected').each(function() {
items.push( this.value );
});
Is this the only way to get the array of values or is there a sleeker way?
Setting the value(s)
var items = ['apple', 'ape', 'carrot'];
$.each(items, function() {
$('select.items option[value="' + this + '"]').prop('selected', true);
});
Is there a sleeker way to do this?
It's quite straight-forward to get the selected values array; use the jQuery .val() method.
var items = $('select.items').val();
//sample result: ["apple","ape","boy","daisy","eagle"]
Please note that JavaScripts value property, which works well for other form fields, returns just the first selected value
function out( v ) {
$('pre.out').text( JSON.stringify( v ) );
}
$('select.items').on('change', function() {
out( $(this).val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="items" multiple="multiple" size="5">
<option value="apple">apple</option>
<option value="ant">ant</option>
<option value="ape">ape</option>
<option value="age">age</option>
<option value="boy">boy</option>
<option value="banana">banana</option>
<option value="carrot">carrot</option>
<option value="cat">cat</option>
<option value="daisy">daisy</option>
<option value="desk">desk</option>
<option value="elephant">elephant</option>
<option value="eagle">eagle</option>
<option value="fox">fox</option>
<option value="fat">fat</option>
<option value="goat">goat</option>
<option value="good">good</option>
<option value="gum">gum</option>
<option value="hut">hut</option>
<option value="hop">hop</option>
<option value="insect">insect</option>
<option value="ice">ice</option>
<option value="jump">jump</option>
<option value="kite">kite</option>
<option value="lamp">lamp</option>
<option value="lap">lap</option>
<option value="monkey">monkey</option>
<option value="mat">mat</option>
<option value="nature">nature</option>
<option value="nose">nose</option>
<option value="owl">owl</option>
<option value="pocket">pocket</option>
<option value="pick">pick</option>
<option value="quote">quote</option>
<option value="rabbit">rabbit</option>
<option value="run">run</option>
<option value="soft">soft</option>
<option value="sit">sit</option>
<option value="table">table</option>
<option value="toy">toy</option>
<option value="understand">understand</option>
<option value="vote">vote</option>
<option value="winter">winter</option>
<option value="xmas">xmas</option>
<option value="yes">yes</option>
<option value="zoo">zoo</option>
</select>
<pre class="out"></pre>
To set the selected values also requires no looping. Use the same jQuery .val() method.
$('select.items').val( ['apple','ape','boy','age','eagle'] );
$('button.set').on('click', function() {
$('select.items').val( ['apple','ape','boy','age','eagle'] );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="items" multiple="multiple" size="5">
<option value="apple">apple</option>
<option value="ant">ant</option>
<option value="ape">ape</option>
<option value="age">age</option>
<option value="boy">boy</option>
<option value="banana">banana</option>
<option value="carrot">carrot</option>
<option value="cat">cat</option>
<option value="daisy">daisy</option>
<option value="desk">desk</option>
<option value="elephant">elephant</option>
<option value="eagle">eagle</option>
<option value="fox">fox</option>
<option value="fat">fat</option>
<option value="goat">goat</option>
<option value="good">good</option>
<option value="gum">gum</option>
<option value="hut">hut</option>
<option value="hop">hop</option>
<option value="insect">insect</option>
<option value="ice">ice</option>
<option value="jump">jump</option>
<option value="kite">kite</option>
<option value="lamp">lamp</option>
<option value="lap">lap</option>
<option value="monkey">monkey</option>
<option value="mat">mat</option>
<option value="nature">nature</option>
<option value="nose">nose</option>
<option value="owl">owl</option>
<option value="pocket">pocket</option>
<option value="pick">pick</option>
<option value="quote">quote</option>
<option value="rabbit">rabbit</option>
<option value="run">run</option>
<option value="soft">soft</option>
<option value="sit">sit</option>
<option value="table">table</option>
<option value="toy">toy</option>
<option value="understand">understand</option>
<option value="vote">vote</option>
<option value="winter">winter</option>
<option value="xmas">xmas</option>
<option value="yes">yes</option>
<option value="zoo">zoo</option>
</select>
<button class="set">SET</button>

Categories