Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Adding and Removing Select Options

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 339
    Comment on it

    A drop-down box for colors and want to add new colors to it, as well as remove options from it.

    <label for="colors">Colors</label>
    <select id="colors" multiple="multiple">
    <option>Black</options>
    <option>Blue</options>
    <option>Brown</options>
    </select>
    <button id="remove">Remove Selected Color(s)</button>
    <label for="newColorName">New Color Name</label>
    <input id="newColorName" type="text" />
    <label for="newColorValue">New Color Value</label>
    <input id="newColorValue" type="text" />
    <button id="add">Add New Color</button>
    

    To add a new option to the drop-down box, use the .appendTo() method:

    // find the "Add New Color" button
    $('#add').click(function(event){
    event.preventDefault();
    var optionName = $('#newColorName').val();
    var optionValue = $('#newColorValue').val();
    $('<option/>').attr('value',optionValue).text(optionName).appendTo('#colors');
    });
    

    To remove an option, use the .remove() method:

    // find the "Remove Selected Color(s)" button
    $('#remove').click(function(event){
    event.preventDefault();
    var $select = $('#colors');
    $('option:selected',$select).remove();
    });
    

 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: