OrangePineapple OrangePineapple - 17 days ago 7
Javascript Question

jQuery: change object's property dynamically

I'm new to JavaScript and jQuery and I'm working on an app and currently having trouble. I have an object's property that I want to change dynamically on a click event, specially toggling.

example code:

var apples = {
value: "$1.00",
propertyIwantToChange: red
};


on click event toggle, the property would become green, and click again it would be red.

propertyIwantToChange: green
-->
propertyIwantToChange: red
-->
propertyIwantToChange: green
and so on.

I was wondering if anyone has any insight for this? Any help is appreciated.

Answer

Using the ternary style with a generic function:

var apples = {
  value: "$1.00",
  propertyIwantToChange: 'green'
};

var toggle = function(obj, prop, first, second) {
  obj[prop] = obj[prop] == first ? second : first;
};

$('input').on('click', function() {
  toggle(apples, 'propertyIwantToChange', 'green', 'red');
  console.log(apples.propertyIwantToChange);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Toggle value" />