Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add and remove select options

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 396
    Comment on it

    To remove an element we use remove() method. The remove() method removes all text, data and events of selected elements.

    To add an item to select option we use append() method.

    Syntax of remove() method:-

    $("#selectBox option[value='option1']").remove();

     

    Append method is used to insert an item at the end of selected element.

    Syntax of append() method:-

    $("#selectBox").append('<option value="option6">option6</option>');

     

    Below is the code to add and remove select options:-

    In the below code the value of the input will be

    HTML-

    <div>
    	<div>
    		<select id="countrylist" style="width: 150px;">
    		    <option value="1">India</option>
    		    <option value="2">Australia</option>
    		    <option value="3">London</option>
    		    <option value="4">Switzerland</option>
    		    <option value="5">Argentina</option>
    		    <option value="6">Bhutan</option>
    		    <option value="7">Canada</option>
    		</select>
    		<input type="button" id="btnDelete" value="Delete" />
    	</div>
    
    		<div id='additem'>
    		    <input type='text' name='addcountry' id="readme"/>
    		    <button class="addoption">Add Country</button>
    		</div>
    </div>

     

    jQuery-

     $(function () {
            $("#btnDelete").bind("click", function () {
            	// on click of delete button the selected option will be removed
                $("#countrylist option:selected").remove();
            });
          });
    
         // on click of add button
        $('.addoption').click(function(){
        	// the value of input will be stored in a variable
            var item = $('input[name=addcountry]').val();
            // the value of input will be appended in select option
            $('#countrylist').append('<option>'+ item +' </option>');
        });

     

    Here is the jsfiddle link of above code:-

    https://jsfiddle.net/8pmL43ma/1/

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: