I am building a Shopping Application with Rails and jQuery. Rails Version 5.1.6. I have an inventories controller and the corresponding inventories.js.
inventories.js
document.addEventListener("turbolinks:load", function() {
function add_item_to_cart(target_elem) {
item = $(target_elem).closest('.grid-item')[0].dataset;
quantity = $(target_elem).next().val();
// and some operation wih the quantity element and item.
}
$('.add-to-cart').on('click',function(){
add_item_to_cart(this);
})
})
The problem is whenever I do $(target_elem).next().val() from console I am getting the value from the quantity input box corectly. But when I execute the jquery inventories.js it says
Uncaught ReferenceError: quantity is not defined
at add_item_to_cart (inventories.self-65782850f63f3dad515dba7e67e72a65016e58fb0751ff2f6342d4183d7d2a0e.js?body=1:10)
at HTMLButtonElement.<anonymous> (inventories.self-65782850f63f3dad515dba7e67e72a65016e58fb0751ff2f6342d4183d7d2a0e.js?body=1:54)
at HTMLButtonElement.dispatch (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:5227)
at HTMLButtonElement.elemData.handle (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:4879)
Also my jquery always returns something like jQuery.fn.init when selecting an element using a selector. Is this an expected behaviour? because I have not faced anything like this before.
item = $(target_elem).closest('.grid-item')
jQuery.fn.init [div.grid-item, prevObject: jQuery.fn.init(1), context: button.add-to-cart]
In my Gemfile
gem 'jquery-rails'
gem 'jquery-turbolinks'
The behaviour is right, in the javascript
you need to denote variable with var
or const
or let
:
var quantity = $(target_elem).next().val();
Otherwise it is undefined variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.