I have a situation where I need to remember what the value of a tagsinput field was before changes were made. However, some of the information is dynamically binded so when the input changes so does the value of my variable that references it.
var topics = $("#topics").tagsinput('items');
$('#topics').tagsinput('add', 'A');
$('#topics').tagsinput('add', 'B');
var LISA = topics;
alert('Lisa is: ' + JSON.stringify(LISA));
$('#topics').tagsinput('add', 'newone');
alert('Lisa is: ' + JSON.stringify(LISA));
So what I'd like is the variable Lisa
to not have newone
added to it.
But with the bootstrap tags input jQuery plugin the variable changes dynamically with the values. Anyone know how to turn off this binding so I can recall what the value of the field was before new information is added?
This has nothing to do with bootstrap-tags per se. It's a byproduct of the way JavaScript creates variables. Consider, for example, the following JavaScript:
var array = ["A", "B"];
var copy = array;
array.push("C");
copy.push("D");
console.log(array);
console.log(copy);
Both array
and copy
will equal ["A", "B", "C", "D"]
The object copy
just contains a reference back to array
so they both resolve to the same object. Updating one updates both. See also: value of an array changes original array.
What you want to do instead is clone an object in javascript, like this:
var LISA = JSON.parse(JSON.stringify(topics));
Now LISA
will not be updated when topics
changes.