views:

2652

answers:

2

I have a dropdownlist:

<select id="ContentList" name="ContentList">
  <option value="">Please Select</option>
  <option value="TEST_TOP">TEST TOP</option>
</select>

I have a sortable list:

<ul id="sortable">
  <li class="ui-state-default">First</li>
  <li class="ui-state-default">Second</li>
  <li class="ui-state-default">Third</li>
</ul>

I have a button:

<input type="button" value="Add Section" id="btnAdd" class="button"/>

And the following script:

<script type="text/javascript">
        $(function() {


            $("#sortable").sortable({
                placeholder: 'ui-state-highlight'
            });
            $("#sortable").disableSelection();

            $('#btnAdd').click(function() {

            });

        });

    </script>

When a user select something in the dropdown list and clicks Add I want that to get sent to the sortable list as an <li> with the class attribute etc, the dropdown to now show the 'Please Select' option.

Not sure the best approach to take. Thanks

+3  A: 
$("#sortable").append("<li class='ui-state-default'>"+
                          $("#ContentList option:selected").text()+"</li>");
$("#ContentList option:selected").remove();

should do the trick... (:

peirix
I went withif ($("#ContentList option:selected").val() != "") { $("#sortable").append("<li class='ui-state-default'>" + $("#ContentList option:selected").val() + "</li>"); $("#ContentList option:selected").remove(); $('#ContentList').attr('selectedIndex', 0); }
Jon
dont embed the html in the js, if you change the markup you then need two changes!! bad
redsquare
seems like a good idea to check the value (: you might also want to check that the default value is not selected, so no one adds "Please Select" to your list...
peirix
+4  A: 

working demo here

$('#btnAdd').click(function() { 

   //cache sortable
   var $sortable = $("#sortable"); 

   //clone sortables first li, change the text to that of the 
   //chosen option and append it to the sortable this saves having 
   //html embedded within the js

   $sortable.children().eq(0)
                       .clone()
                       .text( $('#ContentList').val() )
                       .appendTo( $sortable ); 

   // cache select options
   var $items = $('#ContentList').children(); 

   //remove selected item
   $items.filter(':selected').remove() 

   //set first option to be selected
   $list.eq(0).attr('selected', true); 
});
redsquare
WOW! An answer with a custom demo. Thanks! However your code seems very complex although it could just be me.
Jon
now with comments, not complex really.
redsquare