2 related Multiselect form elements - javascript

I want to create 2 multiselect side by side. The first one is populated, but the 2nd is empty. The 2nd gets populated only when I select an option from the 1st one and depends on the value of the 1st one.
I'm thinking the only way to do this is with javascript. Can someone confirm this, and do you know of existing examples.
I'm using jquery, but prefer to not use plugins.
I'm also thinking to use Zend so if an existing component exists that would be great.

Here's a demo
You can easily do this with some DOM manipulation.
HTML
<select id="from" multiple>
<option value="-">King</option>
<option value="9">Queen</option>
<option value="5">Rook</option>
<option value="3">Knight</option>
<option value="3">Bishop</option>
<option value="1">pawn</option>
</select>
<select id="to" multiple>
</select>
javascript
var from = document.getElementById("from");
var to = document.getElementById("to");
from.onchange = function(){
//remove this to allow for duplicates
to.innerHTML = "";
var fromOptions = from.getElementsByTagName("option");
for(var i in fromOptions) {
if (fromOptions[i].selected == true) {
//remove "cloneNode(true)" to simultaniusly
//remove the node from the from list.
to.appendChild(fromOptions[i].cloneNode(true));
}
}
}

Related

selectmenuchange appending object list only on first event

I have two selectmenus, one of which $('#parent') relates to certain options in the $('#members') menu (related through a data attribute in their HTML). I have a function to limit the choices in 'members' where they relate to the choice selected in the parent menu.
SCRIPT
$("#parent").selectmenu();
$("#members").selectmenu();
var allMembers = $('#members option'); // keep object list of all of the options for the select menu
$("#parent").on("selectmenuchange", function() {
var someMembers = [];
var id = $('#parent option:selected').data('id');
allMembers.each(function() {
if ($(this).data('parent-id') == id) {
someMembers.push($(this))
}
});
$('#members').empty().append(someMembers);
});
At the moment, this works, but only on the first selectmenuchange event - which is odd because using console.log() when the arrays are recreated in the function I can see that the correct have been selected each time, they just don't show in the menu on subsequent changes.
I can't figure out if this is a problem with selectmenuchange or empty().append()
HTML
<select name="members" id="members">
<option data-id="101" data-parent-id="1">Name1</option>
<option data-id="102" data-parent-id="1">Name2</option>
<option data-id="103" data-parent-id="1">Name3</option>
<option data-id="104" data-parent-id="2">Name4</option>
<option data-id="105" data-parent-id="2">Name5</option>
<option data-id="106" data-parent-id="3">Name6</option>
<option data-id="107" data-parent-id="3">Name7</option>
</select>
<select name="parent" id="parent">
<option data-id="1">Parent1</option>
<option data-id="2">Parent2</option>
<option data-id="3">Parent3</option>
</select>
Well the options were changing but it wasn't reflecting in the selectmenu created by plugin. So one of the way is you destroy it and re-initialize the selectmenu as below:
$('#members').html(someMembers).selectmenu('destroy').selectmenu();
DEMO
Instead of selectmenu('destroy') and re-initializing the select menu you can also use selectmenu('refresh'). Refreshing sounds nicer than destroying it each time.
I have updated the fiddle of Guruprasad Rao with the refresh:
fiddle

jQuery getting selected option of dynamically rendered dropdown list

I am working on an MVC + jQuery project, I am creating dropdown list on runtime. After rendering while submitting form through jQuery, I am trying to get selected value. Drop down is rendered and working fine
Also I can check in source code. I am trying to get dropdown list by
$('#Monday_Periods').children('.PeriodRow').each(function () {
var elements = $(this).html();
var found = $('.Subject', elements);
});
I found all objects in variable found, and I can see it in Chrome debug
But after this I am unable to get selected value. As you can see in debug mode that no option is selected. I tried to get by val or text but no luck. Anybody can tell me that how I can get selected value
$(this).html(); is loosing the reference to the DOM (html() returns a String, not a DOM node).
Try to modify in:
var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
console.log($(this).val());
}
or use directly (you already have an id on it!):
$('#subject1').val();
EDIT: SNIPPET ADDED
function printResults(){
$('#Monday_Periods').children('.PeriodRow').each(function () {
var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
console.log($(this).val());
});
});
}
$('#print-results').click(printResults);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Monday_Periods">
<div class="PeriodRow">
<select class="Subject">
<option value="none">-- Select Subject --</option>
<option value="1">Biology</option>
<option value="2">Physics</option>
</select>
<select class="Subject">
<option value="none">-- Select Subject --</option>
<option value="1">Biology</option>
<option value="2">Physics</option>
</select>
</div>
<button type="button" id="print-results">PRINT RESULTS</button>
</form>

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

Populating an input from two drop-downs with Jquery

So I've got an input field that I'm trying to populate using two separate drop-down menus. I've got it working with a single drop-down currently, but I'm unable to do two. Here's an example of what I'm trying to accomplish:
<select type="text" id="make">
<option value="">- select one -</option>
<option value="chevy">Chevy</option>
</select>
<select type="text" id="model">
<option value="">- select one -</option>
<option value="silverado">Silverado</option>
</select>
<input type="text" id="input" value="" />
So the value of the text input should be 'Chevy Silverado' if both fields are selected. Here's the script that I've got so far:
$(function(){
$('select#make').bind('change', function(){
$('input#input').val($(this).val());
});
});
Which works great for one drop down, but obviously does nothing for the other. Any ideas? I've tried a few solutions that I'd found with absolutely no success. Thanks for looking!
Big thanks to those of you who answered my question! With your guidance I was able to get the below code working for me perfectly. Note that I DID add an additional class to my select boxes
$(function(){
var $makemodel = $('.makemodel');
$('.makemodel').on('change',function(){
$('#input').val($makemodel.eq(0).val()+' '+$makemodel.eq(1).val());
});
});
No problem! Please forgive the length of this answer, it offers multiple options depending on whether you place greater importance on code readability vs efficiency. It will only make marginal differences in speed but hopefully it shall inspire you to think of speed in your overall code!
Easy solution:
$('#make,#model').on('change',function(){
$('#input').val($('#make').val()+' '+$('#model').val());
});
More efficient:
Give your selects a class:
<select type="text" id="make" class="MakeModel">
<option value="">- select one -</option>
<option value="chevy">Chevy</option>
</select>
<select type="text" id="model" class="MakeModel">
<option value="">- select one -</option>
<option value="silverado">Silverado</option>
</select>
<input type="text" id="input" value="" />
And then select on the class:
$('.MakeModel').on('change',function(){
$('#input').val($('#make').val()+' '+$('#model').val());
});
Giving it a class just makes it slightly easier for the parser to query only one selector rather than two.
Most efficient:
Use the appropriate .eq() values and caching instead of querying the ID selectors again:
var $makemodel = $('.MakeModel');
$makemodel.on('change',function(){
$('#input').val($makemodel.eq(0).val()+' '+$makemodel.eq(1).val());
});
This means the select items do not need to be requeried since all the objects of .MakeModel are contained within the function under the cached $makemodel and you can just specify the object order number to reference a specific one.
jsFiddle to show what I mean here
Additional notes:
Notice the use of .on rather than .bind, which is the more correct syntax for modern jQuery applications.
Also, using tagnames before ID or class will actually make your selectors less efficient, as the parser needs to verify the ID/class is associated with the tag, rather than just grabbing the ID (which should be unique anyway) or class name (which should be appropriately isolated in its naming).
Simple solution:
$(function() {
$('#make, #model').on('change', function() {
var makeCurr = $('#make').find(":selected");
var madelCurr = $('#model').find(":selected");
var make = (makeCurr.val() != '') ? makeCurr.text() : '';
var model = (madelCurr.val() != '') ? madelCurr.text() : '';
$('input#input').val(make + ' ' + model);
});
});
View Example
I'd suggest amending the HTML somewhat, to group the select elements within a single parent, and binding, using on(), the change event to that element:
<form action="#" method="post">
<fieldset>
<select type="text" id="make">
<option value="">- select one -</option>
<option value="chevy">Chevy</option>
</select>
<select type="text" id="model">
<option value="">- select one -</option>
<option value="silverado">Silverado</option>
</select>
<input type="text" id="input" value="" />
</fieldset>
</form>
With the jQuery:
$('fieldset').on('change', function(){
var self = $(this);
$('#input').val(function(){
return self.find('select').map(function(){ return this.value; }).get().join(' ');
});
});
JS Fiddle demo.
Modifying further, to use a class to identify the summary element (the text-input into which the value will be inserted) reduces the reliance on known elements, and allows for more general-purpose code:
$('fieldset').on('change', function(){
var self = $(this);
self.find('.summary').val(function(){
return self.find('select').map(function(){ return this.value; }).get().join(' ');
});
});
JS Fiddle demo.
And a non-jQuery, plain-JavaScript approach to the same solution (albeit only works in those browsers that support document.querySelector()/document.querySelectorAll() and addEventListener()):
function summarise(container, what, sumClass) {
var els = container.querySelectorAll(what),
sumTo = container.querySelector(sumClass),
vals = [];
for (var i = 0, len = els.length; i < len; i++) {
vals.push(els[i].value);
}
sumTo.value = vals.join(' ').trim();
}
var fieldsets = document.querySelectorAll('fieldset');
for (var i = 0, len = fieldsets.length; i < len; i++) {
fieldsets[i].addEventListener('change', function(){
summarise(this, 'select', '.summary');
}, false);
}
JS Fiddle demo.

Jquery - Grab multiple selections' data in Jquery

This originates from my original question. I'm expanding on it.
Html select options
<select id="1d" name="camp" multiple="multiple">
<option data-url0="week_1" value="Week 1">30th July</option>
<option data-url1="week_2" value="Week 2">6th August</option>
</select>
<input type="hidden" name="camp_url0" id="1e">
<input type="hidden" name="camp_url1" id="1f">
Jquery script I'm struggling with.
$("#1d").on("change", function () {
var url1 = $(this).children(":selected").data("url0");
var url2 = $(this).children(":selected").data("url1");
$("#1e").val(url0);
$("#1f").val(url1);
});
This code works beautifully (maybe not the cleanest?), except for one important issue. Even though it is a multiple selector, whenever both options are selected, only one option is marked as :selected in DOM, meaning only one data-url{row_id} is being inputted. I need both, if both are selected.
I hope that makes sense. Thanks for your help.
UPD:
Add some additional “routing” data to the html
<select id="1d" name="camp" size="5" multiple>
<option data-url="week_1" data-id="1e" value="Week 1">30th July</option>
<option data-url="week_2" data-id="1f" value="Week 2">6th August</option>
</select>
and use it
$("#1d").on("change", function () {
$('input[type=hidden]').val('');
$('option:selected', this).each(function() {
$('#' + $(this).data('id')).val($(this).data('url'))
})
})
http://jsfiddle.net/5ctDC/1/
OLD:
Just .map it and you will get an array with the data.
$('option:selected', this).map(function() {
return $(this).data('url')
})
["week_1", "week_2"]
http://jsfiddle.net/5ctDC/
Go through ALL of the selected elements:
$("#1d").on("change", function () {
var allurl1 = '', allurl2 = '';
$(this).children(":selected").each(function(){
allurl1 += $(this).data("url0");
allurl2 += $(this).data("url1");
});
$("#1e").val(allurl1);
$("#1f").val(allurl2);
});
Working Demo: http://jsfiddle.net/maniator/mtAgS/ (I made the inputs shown so you can visually see what happens)
In an unrelated note, you should'nt be using id that don't start with a letter.

Categories