Wednesday, 29 January 2014

Move options from one dropdown to other using jQuery

Today while looking for a way to move options from one dropdown to other dropdown, onclick of some link or button, I discovered one easy and you can say most optimized way to do so. Please follow the same below.

Scenario:
Here suppose we have two dropdowns having id as dropdown1 and dropdown2. I want to move options from dropdown1 to dropdown2 onclick of a link as add and in reverse way on click on remove link I want to take options out from dropdown2 and put the same in dropdown1.

How to do it?
On click of add link we can give call to method as: moveOptions(dropdown1, dropdown2) and similarly on click of remove link we can call to method moveOptions(dropdown2, dropdown1). Mark here I just altered the position of the dropdowns in the method call.

So here goes the method.

function moveOptions(sourceId, sinkId){

     $("#" + sinkId).append($("#" + sourceId + " option:selected"));

}

This single line method will be enough to add and remove options from a dropdown and remove and add in other.
Calling the method:

<!-- First dropdown -->

<select id="dropdown1">

<option value="1">one</option>

<option value="2">two</option>

<option value="3">three</option>

</select>



<!-- Second dropdown -->

<select id="dropdown2">



</select>



<!-- Links to add and remove options -->

<p onclick=" moveOptions(dropdown1, dropdown2)">Add</p>

<p onclick=" moveOptions(dropdown2, dropdown1)">Remove</p>

No comments:

Post a Comment

Embedding Power BI Report Using ColdFusion

Recently I got an opportunity to embed power BI reports in ColdFusion Application. Please find the steps and requirements below for implem...