javascriptjquerytaffydb

Using JS variable in TaffyDB query returns undefined


I have a TaffyDB containing recipes for items from an RPG. Each item has a boolean to declare whether it's been "mixed" in the game.

var recipes = TAFFY([
    {id:0, name:'Potion', mixed:false},
    {id:1, name:'Hi-Potion', mixed:false},
    {id:2, name:'Mega-Potion', mixed:false}
]);

An HTML table is generated with each recipe having a checkbox representing the "mixed" variable. Each checkbox has value=X where X corresponds to the ID of the item in the database. I detect checkbox changes and attempt to update the data using the following:

$('input:checkbox').on('change', function() {
    var val = $(this).val();
    var checked = $(this).is(':checked');

    recipes({id:val}).update({mixed:checked});

    alert('Updated recipe id: ' + val + 
      '\nRecipe: ' + recipes({id:val}).first().name +
      '\nValue should be ' + checked +
      '\nValue is ' + recipes({id:val}).first().mixed);
}

When attempting to get the variables by using recipes({id:val}).first().name and .mixed, undefined is always returned. The update call doesn't change the values either. However, if I change all of the queries to recipes({id:0}), it works fine but it only reports and updates the first checkbox.

As far as I can tell, it doesn't like the javascript variables val and checked when doing doing queries such as recipes({id:val}), but is fine with the literal 0.

JSFiddle: http://jsfiddle.net/w6g6W/12/


Solution

  • It turned out that $(this).val() was returning a string, not an int.

    Replaced var val = $(this).val(); with var val = parseInt($(this).val());