Is there a better way to insert an option in select with jquery?

Question:

I wanted to know if there is a better way to insert an option in select with jquery.

Example:

<select name="municipio_evento" id="municipio_evento">
<option value=""></option>
<option value="1">ACEGUA</option>
<option value="2">AGUA SANTA</option>
<option value="3">AGUDO</option>
<select>

I know I can do it this way:

$('#municipio_evento').append('<option value="4">AGUAS CLARAS</option>');

If anyone has any suggestions or ideas I would appreciate it.

Answer:

You can instantiate an Option class from the DOM.

 var option = new Option('TESTE','4');
 $('#municipio_evento').append(option);

You can test it working in JSFiddle, follow the Test Option Append link:

Note: I recommend using this inside a function to facilitate future reuse.

Scroll to Top