Set selected value in multiple select list - javascript

I have this multi select list:
<select id="vendors" name="vendors" multiple="multiple">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
<option value="5">E</option>
</select>
When the page loads, I'm loading a list of ids that need to be selected in my select list. Here's how I'm trying to do it:
var vendors = GetVendorArray(); // list of vendor ids I want selected
$.each(vendors, function(index, item) {
$("#vendors").filter(function() {
return $(this).val() == item;
}).attr('selected', true);
});
But this doesn't work, none of the items are being selected. Anyone know what I'm doing wrong?

Simplest approach is just pass the whole array as value to the select using val(). With mulitple select value is an array
$('#vendors').val( GetVendorArray())
DEMO:http://jsfiddle.net/sPKAY/
The problem with approach you took was not looping over option tags

filter reduces the set of matched elements to match the additional selector/callback fn. output. You need to target the <option> elements, not the drop-down list itself, since you're trying to select the option based on whether its value matches your array contents.
var vendors = GetVendorArray(); // list of vendor ids I want selected
$.each(vendors, function(index, item) {
//you're filtering options, not the list itself
$("#vendors > option").filter( function() {
return $(this).val() == item;
}).prop('selected', true); //use .prop, not .attr
});

Related

Hierarchical Select List using jQuery

I have two select list,
Select list 1 contains the Mobile phone brands names
<select name="mobile-phone" class="mobile-phone">
<option value="Select">Select</option>
<option value="Nokia">Nokia</option>
<option value="Samsung">Samsung</option>
<option value="HTC">HTC</option>
<option value="Apple">Apple</option>
</select>
Select list 2 contains the phone type like
<select name="mobile-model" class="mobile-model">
<option value="Select">Select</option>
<option value="Nokia--Lumia-520">Lumia 520</option>
<option value="Nokia--Lumia-620">Lumia 620</option>
<option value="Samsung--Galaxy-s3">Galaxy S3</option>
<option value="Samsung--Galaxy-s4">Galaxy S4</option>
<option value="HTC--hero">Hero</option>
<option value="HTC--one">One</option>
<option value="Apple--iphone4">iPhone 4</option>
<option value="Apple--iphone5">iPhone 5</option>
</select>
My quest is I want to display Select list 2 according to the value users select in Select List 1.
If a user selects Nokia in first selection, then only Lumia phones should be shown in second select list. Like so, for other phones.
When None is selected in First select list, then second select list should not show anything, but still visible without any option (like disabled button).
How can I accomplish this using jQuery?
The JSFiddle I have made from above select list.
I'd suggest:
/* select the select element whose name is "mobile-phone",
assign an event-handler for the 'change' event:
*/
$('select[name="mobile-phone"]').change(function () {
// get the relevant/selected brand-name:
var brand = this.value;
/* find the option elements inside of the select element with
name="mobile-model", enable them all:
*/
$('select[name="mobile-model"] option').prop('disabled', false)
// show them all:
.show()
// filter the collection, to find only those whose value does not start with the brand-name:
.filter(function () {
return !(this.value.indexOf(brand) === 0);
})
// disable those elements:
.prop('disabled', true)
// hide them:
.hide();
});
JS Fiddle demo.
References:
Attribute-starts-with ([attribute^="value"]) selector.
filter().
hide().
prop().
show().
I think you are looking for:
$("#sel2").prop("disabled", true);
$( "#sel1" ).change(function() {
var value = $(this).val();
$("#sel2").prop("disabled", false);
$("#sel2 > option").hide();
$("#sel2 > option[value*='" + value +"']").show();
});
Only I put to selects Id for do the selection by Jquery more easy. Before I disabled the control wating for any selection, and when the first select change only I keep the option that macth with option[value*='" + value +"']".
Live demo here
There is a jQuery plugin that handles this exact case very nicely: http://www.appelsiini.net/projects/chained .
You should consider having two MySQL tables: brand, model. The brand table would just be a list of brands with IDs. The model table would contain a brand column where you input those IDs.
Then you should do a JSON query for the brand selected, and return a select list accordingly.
By doing it this way, you'll have an in depth database that you can call and manipulate in numerous ways.
Alternatively, you could do something like:
$(".mobile-phone").on("change", function(){
var brand = $(this).val();
$("[data-brand]").hide();
$("[data-brand="+brand+"]").show();
});
And do this:
<option data-brand="Nokia" value="...

JavaScript Multi Select Box not posting all items

I found a nice demo on an old JSFIddle for Moving items from one multi-select box to another with JavaScript
You can see the demo here: http://jsfiddle.net/jasondavis/e6Y7J/25/
The problem is, the visual part works correctly but when I put this on a server with PHP, it only POST the last item added to the new select box. So instead of POSTING an array of items, it will only POST 1 item regardless of how many items exist in the selection box.
Can anyone help me?
The JavaScript/jQuery
$(document).ready(function() {
$('select').change(function() {
var $this = $(this);
$this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
});
});
I believe I've hit this issue before. For the PHP $_POST array to populate this correctly you need to add a name field with [] at the end of the name. PHP will then interpret the result as an array of all the values and not just the last selected one.
Example:
<select name="demo_multi[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
When you recall the item in the $_POST array leave off the square brackets.
$values = $_POST['demo_multi'];
Change the multiselect name to an array
<select name="post_status[]" multiple id="select2" class="whatever" style="height: 500px; width: 222px;"></select>
I think you also have to select all items in the
This is pre jquery but it works.
`<form onsubmit="selectAll();"> ....</form>
function selectAll()
{
for(j=0; j<document.formdata.elements.length; j++)
{
// if a multiple select box then select all items in the box so they are sent with the form
var currObj = document.formdata.elements[j];
if (currObj.tagName == 'SELECT' && currObj.multiple == true)
for (i=0; i<currObj.length; i++)
currObj.options[i].selected = true;
}
}`
This will then be loaded into the array named in the

In Jquery Chosen plugin remove selection if user selects a particular value

I have the following multi select and I am using Jquery Chosen plugin
<select multiple="multiple" class="chzn-select span3" name="requestCategory" id="requestCategory">
<option selected="selected" value="">All</option>
<option value="2">Electrical</option>
<option value="4">Emails</option>
<option value="3">Filming Permits</option>
<option value="10">test1</option>
</select>
Client wants to make sure that i do not allow user to select ALL if any other value is selected or if user selects any other value then automatically deselect/remove ALL; because ALL = all categories so having individual option does not make sense. How do i do this?
Check if more than one item is selected, or if only one item is selected that it is not the first one - in these cases disable All.
$('.chzn-select').on('change', function() {
var selectedOpts = $('option:selected', this);
if(selectedOpts.length > 1 || selectedOpts.first().index() !== 0) {
$('option', this).first().attr('disabled', 'disabled');
}
});​
http://jsfiddle.net/zCk2z/5/
at first change of option [simple] removes the All category.
but i recomand to disable the item, it looks better use .attr('disabled', 'disabled') instead of .remove();
$('#requestCategory').change(
function(){
$(this).find('option:contains("All")').remove()
})

How to select option in jQuery using text of option tag

I'm trying to select a certain option in a select box, but it's not working:
var category = $(row + 'td:nth-child(4)').text();
$('#category_id', theCloned).load('/webadmin/video/get_categories',function(){
$('#category_id', theCloned).val(category);
});
There's no error thrown, but it doesn't change the select box. What am I doing wrong here?
Here is an example of the options loaded by the load() call:
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
The value of the category variable is "Fun" or "Capabilities", etc.
var $selectbox = $('#category_id', theCloned), // cache the element to avoid lookup overheads
category = $(row + 'td:nth-child(4)').text();
$selectbox.load('/webadmin/video/get_categories', function(){
$selectbox
.find('option')
.filter(function(){
return $(this).text() === category;
})
.prop('selected', true);
});
Update 1
Updated the code to adjust to the code you presented in your update. This will work. However if an option will contain a part of the string and not the full string it will still be part of the selected elements. E.g.
If the options will be
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
<option value="6">Fun Time</option>
<option value="6">Funhouse</option>
And the category variable will have the value Fun, all three last options will be part of the selector.
Update 2
Changed the code to filter the options whose text fully matches the value of the category variable. Thus, you won't have to worry about the Update 1 above.
$('#id_of_select_box').val('your_value');
this will do
Try this
$('#category_id', theCloned).val($.trim(category));
At last i found a new solution Fiddle
<select>
<option value='1'>one</option>
<option value='2' >two</option>
<option value='3' >three</option>
</select>
Script
$("select").on("change",function(){
alert($("select option:selected").text());
});

Jquery/Javascript link $(this) to an element in a different div?

I've got a multiple select that I want to use to pick which elements show up in an HTML template window. So I have several options that I want to iterate over, and based on whether it's been selected, make the preview elements visible or hidden.
I'm going for something like this:
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
$(??????).css($css);
});
As you can see, I'm just iterating over each option (I'm pretty sure that syntax works) in my area_select menu, but I don't know how to make the css get applied to the corresponding piece.... how can I reference my preview elements via my options?
An easier way to go is to call .val() on the multiple select. That returns an array of selected values that you can iterate over.
var array = $('#area_select').val()
$.each(array, function(i,val) {
// your code
});
So as far as showing the elements is concerned, it would depend on what type of data is stored in the value of the select options.
For an ID, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('#' + value).css('visibility','visible');
});
Or if they are class names, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('.' + value).css('visibility','visible');
});
Give each of the options a name corresponding to the ID of the correct piece.
e.g.
<select>
<option value="whatever">Whatever</option>
<option value="whatever2">Whatever 2</option>
</select>
Then each of you elements will be contained in a a div like this:
<div id="whatever-preview">
<!-- Whatever -->
</div>
Then your Javascript
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
var div_name = "#" + $(this).attr('value') + "-preview";
$(div_name).css($css);
});
Give each option an id referencing the id of the corresponding element in the preview window.
for instance:
<option id="option-1">This turns on the first option element in the preview window</option>
<option id="option-2">This turns on the first option element in the preview window</option>
and give the preview window elements similar-ending ids:
<div id='window-1'>corresponding window preview element</div>
Then in the javascript:
$("#window-" + $(this).attr('id').split('-')[1]).css($css);
First, give the elements to hide or show the same class but id's matching the options values:
<div class="something" id="val_1">content1</div>
<div class="something" id="val_2">content2</div>
<div class="something" id="val_3">content3</div>
<div class="something" id="val_4">content4</div>
<select id="area_select">
<option value="val_1">val 1</option>
<option value="val_2">val 1</option>
<option value="val_3">val 1</option>
<option value="val_4">val 1</option>
</select>
then, when the select choosen option changes hide all the stuff and show the selected
$('#area_select').change( function(){
var val = $(this).val();
$('.something').hide();
$('#'+val).show();
return false;
});

Categories