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

5

I wanted to know if there is a better way to insert option into 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, thank you.

    
asked by anonymous 07.10.2014 / 19:50

3 answers

3

You can instantiate a DOM Option class.

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

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

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

    
08.10.2014 / 00:52
3

The most correct answer is a big depend .

The form you've laid out is basically the pattern. Almost all examples of official documentation basically do this, use the append method to transform strings into elements and add them to a parent element of a single stroke.

Another alternative is to first create the element, then insert:

var opcao = $("<option value='foo'>bar</option>");
$("#teuSeletor").append(opcao);

That tends to be more readable and organized, when more code is involved.

The question of which way is best depends on the context in which you will use it. If all you are going to do is add an option once and go, it is no problem doing as you are already doing. If you're going to use repeat structures and / or generate options dynamically, the second way usually makes your code easier to test and maintain.

    
07.10.2014 / 19:58
2

I think the best way to work with large lists in HTML + JS is to use a JSON that can even be in some external file, easier to change later, something like:

<select name="municipio_evento" id="municipio_evento"></select>
<script>

    html = "";
    obj = {
        "1" : "ACEGUA",
        "2": "AGUA SANTA",
        "3" : "AGUDO"
    }
    for(var key in obj) {
        html += "<option value=" + key  + ">" +obj[key] + "</option>"
    }
    document.getElementById("municipio_evento").innerHTML = html;

</script>

I hope I have helped.

    
07.10.2014 / 23:13