Nadeemmnn Mohd
Nadeemmnn Mohd

Reputation: 724

Dynamically adding and removing items to select jquery

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/

Upvotes: 0

Views: 1366

Answers (1)

Paul Roub
Paul Roub

Reputation: 36458

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.

Upvotes: 1

Related Questions