I’m trying to translate this script to jQuery. See rails casts #88
var colors = new Array();
<%= for color in @colors %>
colors.push(new Array(<%= colot.product_id %>, '<%= color.name %>', <%= color.id %>));
<% end %>
function productSelected() {
product_id = $('order_items_attributes_0_product_id').val();
options = $('item_color_id').options;
colors.each(function(color) {
if (color[0] == product_id) {
options[options.length] = new Option(color[1], color[2]);
}
});
if (options.length == 1) {
$('color_field').hide();
} else {
$('color_field').show();
}
}
$(document).ready(function() {
productSelected();
$('order_items_attributes_0_product_id').change(productSelected);
});
Firebug says
TypeError: 'undefined' is not a function (evaluating 'colors.each(function(color) {
if (color[0] == product_id) {
options[options.length] = new Option(color[1], color[2]);
}
})')
Also the ruby code is no longer allowed in 3.1.1 js files (under assets)? It also complains about SyntaxError: Unexpected token '<'
Your implementation of
.eachis wrong. Use:colorsis an array, which does not have the JQuery.eachmethod. The$.eachfunction accepts to parameters:See also