Meaning of append syntax

Asked

Viewed 220 times

11

$("#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 didn’t understand mainly the part between keys.

 $("#cities2").append($("<option>", { text: city, selected: "selected"})).change();           

2 answers

11


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

{ text: city, selected: "selected"}

11

This line does 4 things:

#1: selects the element with ID cities2

This is the basic functionality of jQuery, select DOM elements, meste case probably <select id="cities2">. The equivalent in native Javascript would be

document.getElementById('cities2');

#2: creates a new element option

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

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

#3: Add it in select with .append()

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

#4: fires an event change

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.