I am creating an EC site with Rails. When adding an item to the cart, I wanted to display a pop-up like the one below if there was no quantity selected. This time is the memorandum.
The page in the above picture is the following View file.
.showMain
.showMain__Boxes
.showMain__Boxes__leftBox
= image_tag @product.image, width: 450, height: 450, class: "showMain__Boxes__leftBox__image"
.showMain__Boxes__rightBox
= form_with url: add_item_carts_path, local: true, name: "formForCart" do |f|
.showMain__Boxes__rightBox__name
= @product.name
.showMain__Boxes__rightBox__namejap
= @product.namejap
.showMain__Boxes__rightBox__description
= @product.description
.showMain__Boxes__rightBox__orderQuantity
= f.label :quantity, "quantity", class: "showMain__Boxes__rightBox__orderQuantity__title"
= f.select :quantity, stock_array_maker(@stock), {include_blank: "Please select"}, {class: "showMain__Boxes__rightBox__orderQuantity__form"}
.showMain__Boxes__rightBox__line
.showMain__Boxes__rightBox__line__price
= "Base price: ¥#{convertToJPY(@product.price)}"
.showMain__Boxes__rightBox__line__fav
- if user_signed_in? && current_user
- if @product.bookmark_by?(current_user)
= link_to product_bookmark_path(@product.id), class: "showMain__Boxes__rightBox__line__fav__btn.fav", method: :delete, remote: true do
%i.fas.fa-star.star
- else
= link_to product_bookmarks_path(@product.id), class: "showMain__Boxes__rightBox__line__fav__btn.fav", method: :post, remote: true do
%i.far.fa-star.star-o (Add to Favourites)
.showMain__Boxes__rightBox__line
.showMain__Boxes__rightBox__addCart
= f.hidden_field :product_id, value: @product.id
= f.hidden_field :cart_id, value: @cart.id
= f.submit "Add to Cart", {class: "showMain__Boxes__rightBox__addCart__btn", id: "addToCart"}
I'm getting two nodes, a submit tag and a quantity select tag.
$(function(){
$("#addToCart").on('click', function(e){
if(document.getElementById('quantity').value === ""){
alert("Please select a quantity.");
return false;
}else{
return true;
}
})
});
Set to fire when the submit button of the form is pressed, and if there is no id value of = f.select: quantity ~, it returns false and warns with an alert. If the return value is true, it will be submitted, and if it is false, it will not be submitted. By the way, if there is no "return false", a pop-up will appear, but you will be taken to the next page.
$(function(){
$("#addToCart").on('click', function(e){
if(!(document.getElementById('quantity').value)){
alert("Please select a quantity.");
return false;
}else{
return true;
}
})
});
How to check form input with JavaScript [JavaScript] How to check empty strings [Study]
Recommended Posts