Syntax, meaning

10
$("#add_city_btn2").click(function() {
    var city = $("#add_city2").val();
    $("#cities2").append($("<option>", { text: city, selected: "selected"})).change();
    $("#add_city2").val('');
    return false;
});   

What does the line below this code mean? I did not understand mainly the part in braces.

 $("#cities2").append($("<option>", { text: city, selected: "selected"})).change();           
    
asked by anonymous 13.10.2015 / 17:42

2 answers

10

A new option is created with the text (description), which is contained in the city variable and is marked as selected option selected.

{ text: city, selected: "selected"}
    
13.10.2015 / 17:44
10

This line does 4 things:

# 1: selects the element with ID cities2

This is the basic functionality of jQuery, selecting elements from the DOM, meste if probably <select id="cities2"> . The native JavaScript equivalent would be

document.getElementById('cities2');

# 2: Creates a new element option

$("<option>", { text: city, selected: "selected"}) creates a new element that stays in HTML with this look:

<option selected="selected"><o valor da variavel city></option>

# 3: Adds it to select with .append()

Here jQuery inserts this new element at the end of the <select> descendants. The native equivalent is .appendChild() .

# 4: triggers an event change

This previous code (in # 1, # 2, and # 3) changes the selected option to select. However since this is done programmatically and not by user interaction it is necessary to trigger the change event to other parts of the code that are waiting to run when the select has been changed.

    
13.10.2015 / 19:00