Cliffe
Cliffe

Reputation: 107

variable and selector with JQuery

Can you explain the difference

between this:

$(document).on("change", "#domaine_uid", function() {
    $("#site_uid").empty();
});

and this:

const site_uid = $("#site_uid");
$(document).on("change", "#domaine_uid", function() {
    site_uid.empty();
});

Why does the second code does not work?

Upvotes: 0

Views: 26

Answers (2)

David
David

Reputation: 218818

The first one evaluates the $("#site_uid") in the click handler, so it is applied to any matching element found when the click handler executes.

The second one evaluates the $("#site_uid") once, and only once, right away. So it is applied to any matching element found when the page loads.

Presumably the target element is added after the page loads.

Upvotes: 2

Niek Nijland
Niek Nijland

Reputation: 772

The second code does not work because you're saving $("#site_uid") inside a const (constant). const cannot be edited after declaration.

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Statements/const

Use let or var.

Upvotes: 0

Related Questions