Select multiple values ​​in a multiple select box using jQuery

So, I have two multiple selection blocks, for example

<select id="foo" multiple="multiple"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> <select id="bar" multiple="multiple"> <option value="1">Opt 1</option> <option value="2">Opt 2</option> <option value="3">Opt 3</option> <option value="4">Opt 4</option> </select> <a href="#" onclick="select()">Select</a> 

What I'm trying to do is that when I click "Select" any parameter in "#bar" will be selected, which has the same value with the option in "#foo". In this case, select Opt 1 and Opt 2 in "#bar". I don't know why my javascript will not work. I know that this should be something very simple. I just can't see it. :( Therefore, my Javascript function is executed as follows:

 function select(){ var vals = new Array(); var iter = 0; $("#foo option").each(function(){ var v = $(this).val(); $('#bar option').each(function(){ if ($(this).val() == v) { vals[iter] = v; iter++; break; } }); }); $("#bar").val(vals); } 
+8
javascript jquery multiple-select
source share
2 answers

UPDATE after viewing the KON example

Demo

 $("#sel").click(function(e) { e.preventDefault(); // cancel the link itself $("#bar").val($("#foo").val()); }); 

 <a href="#" id="sel">Select</a> 

An older example using each

Demo

 $("#sel").click(function(e) { // when link clicked e.preventDefault(); $("#foo option:selected ").each(function(){ var v = $(this).attr("value"); // first select value $('#bar option').each(function(){ if ($(this).attr("value") == v) { $(this).attr("selected",true); // select if same value } }); }); }) 
+5
source share

Check this out http://jsfiddle.net/NtF8J/

HTML

 <select 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> <select 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> <button> random </button>​ 

JQuery

 $(function(){ $(document.body).delegate( 'select:first', 'change', function(){ $('select:not(:first)').val( $(this).val() ) } ) .delegate( 'button', 'click', function(){ $('select').val([1,2,3,4].filter(function(){return!!Math.round(Math.random() * 1)})) } ) });​ 
+5
source share

All Articles