1

I need to append an option between two options.I have found so many answers regarding appending an option using jquery.But there the option is appending to the last.But i need to be between two options.

I need to insert the new option between 2 & 3. How can I do it?

$(document).ready(function() {
  var option = $('<option disabled="disabled" value="">-------------------------</option>');
  $('#country').append(option);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4'>4</option>
</select>

2 Answers 2

2

You could do this by using insertAfter() and targeting the option by its index with :eq():

jQuery($ => {
  var $option = $('<option disabled="disabled" value="">-------------------------</option>');
  $option.insertAfter('#country option:eq(1)');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

Or alternatively you could select the target by its value:

$option.insertAfter('#country option[value="2"]');

Or you could use insertBefore() and select the third element instead.

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

2 Comments

Thanks for the answer.Apart from the question can i insert a <hr> instead of --------- as option
No. Only <option> and <optgroup> elements can be children of a select. Not a <hr />
1

Try .after() or .before() depending on what your reference point is.

$(document).ready(function () {
    var option = $('<option disabled="disabled" value="">-------------------------</option>');
    $('#country option[value="2"]').after(option);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>

</select>

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.