Im populating/inserting jsonObjects[i].type
in a menu
with a div
called #changetotypes
. Im getting values r
, c
and e
from jsonObjects[i].type
in a menu, know I wanna be able to click on does value r
, c
and e
and change the values to the clicked value. Know I can click on a object and It is displaying the value r
, c
or e
.
So If I click on a object It gets/display the value jsonObjects[i].type
r
, c
or e
in a menu that the object have. Know how can I change my clicked objects value example from r
to c
?
<li>
<a href="#">Typs</a>
<ul>
<li>
<a href="#"><span id="currenttype" title=""></span></a>
<ul id="changetotypes"></ul>
</li>
</ul>
</li>
function populateTypes() {
for(i = 0; i < jsonObjects.length; i++) {
if(availableTypes.indexOf(jsonObjects[i].type) < 0) {
availableTypes.push(jsonObjects[i].type);
$("#changetotypes").append('<li><a href="#">' + jsonObjects[i].type + '</a></li>');
}
}
}
You can try something like the following (jsFiddle). Assuming jsonObjects comes from somewhere else.
function populateTypes() {
var availableTypes = [];
for(var i = 0; i < jsonObjects.length; i++) {
if(availableTypes.indexOf(jsonObjects[i].type) < 0) {
availableTypes.push(jsonObjects[i].type);
$('<li><a href="#">' + jsonObjects[i].type + '</a></li>')
.data('type', jsonObjects[i].type)
.on('click', function(){ $('#currenttype').text($(this).data('type')); })
.appendTo('#changetotypes');
}
}
}
Here when we create the <li/> element for a specific type, we add a click handler at the same time that changes the text of the currenttype element.
We store the type we want to change currenttype to in the data of our <li/> element so we don't have to worry about closures in the loop, but there are other ways to solve that problem as well, like creating a function that returns a function (see link) or using the contents of the <a/> element (as in $('a', $(this)).text()).