0

Dynamically adding and removing items to select jquery

Here is the example to add and removing items dynamically using jquery to select

html

<select id="List" class="form-control pull-left" style='width:40%'>
<option value="select">Select</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="new">new</option>
    <option value="old">old</option>
</select>
<input type="button" id="delete"
 value="delete" class="btn btn-danger" />
<br />

<input type='text' id="readme" class='form-control pull-left' style="width:40%" /><input id="add" class="btn btn-success" type="button" value="add" /><br />

<div class="result"></div>

JQUERY

$('#add').on('click',function(){
    $("#List").append('<option>'+$('#readme').val()+'</option>');
    $('.result').html('1 item added to select list').hide(2000);
});
$('#delete').on('click',function(){
    $("#List option:selected").remove();
    $('.result').html('1 item deleted to select list').hide(2000);
});

Demo:

http://jsfiddle.net/bxsnevzs/3/

4
  • 4
    And what is your question? Commented Jan 15, 2015 at 20:03
  • @EWit, Now that's a good question... Commented Jan 15, 2015 at 20:05
  • Vote it if am right check demo or let me know best way to achieve this Commented Jan 15, 2015 at 20:07
  • WHAT IS THE QUESTION ? Commented Jan 15, 2015 at 20:10

1 Answer 1

1

Everything seems to work, except that notifications ("1 item added...") aren't seen after the first add or delete. You can fix that by making sure to show() the results div first.

$('#add').on('click',function(){
  $('<option>').
    text( $('#readme').val() ).
    appendTo('#List');
  $('.result').html('1 item added to select list').show().hide(2000);
});

$('#delete').on('click',function(){
  $("#List option:selected").remove();
  $('.result').html('1 item deleted from select list').show().hide(2000);
});

Also, using text() instead of concatenating strings avoids problems if a user enters HTML into the input field.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.