Inchara Raveendra Inchara Raveendra -3 years ago 43
jQuery Question

Add a new option to select on click of "Other" in jQuery

On choosing "Other", input box should appear whose value will be appended to as an

After adding the new option, "Other" should still be there in the dropdown. How to achieve this?

<select class="form-control" id="category" name="category">
<option>Notification</option>
<option>Other</option>
</select>


Input box:

<input type="text" value="">


After you add value "Alert" as an option, this should be the structure,

<select class="form-control" id="category" name="category">
<option>Notification</option>
<option>Alert</option>
<option>Other</option>
</select>

Answer Source

Here is my solution for you. First change option's text by your input value and after add new option with the text "Other".

$(document).on('click', '#add', function(){
    if($('#new-option').val() != '')
    {
        var val = $('#new-option').val();
        $('#foo option:last').html(val);
        var opt = '<option>Other</option>';
        $('#foo').append(opt);
    } 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<select id="foo">
  <option>Notification</option>
  <option>Other</option>
</select>

<input type="text" id="new-option" required>
<button type="button" id="add">Add Option</button>
    

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download