はじめに
RailsでECサイトを作成しています。
カートに商品を追加する時に、数量選択がなかった場合に以下のようなポップアップを表示させたいと思いました。今回はその備忘録です。

補足情報
- Ruby 2.5.1
 - Ruby on Rails 5.2.4.2
 
フォームの内容
上記写真のページは以下のようなViewファイルになっています。
.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, "数量", class: "showMain__Boxes__rightBox__orderQuantity__title"
          = f.select :quantity, stock_array_maker(@stock), {include_blank: "選択してください"}, {class: "showMain__Boxes__rightBox__orderQuantity__form"}
        .showMain__Boxes__rightBox__line
          .showMain__Boxes__rightBox__line__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 (お気に入りに追加)
        .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"}
JSの記載方法
submitタグ、quantityのselectタグの2つのノードを取得しています。
$(function(){
  $("#addToCart").on('click', function(e){
    if(document.getElementById('quantity').value === ""){
      alert("数量を選択してください。");
      return false;
    }else{
      return true;
    }
  })
});
フォームのsubmitボタンが押された時に発火するように設定をして、= f.select :quantity ~ のidのvalueがない場合にfalseを返し、アラートで警告します。
返り値がtrueならサブミットし、falseならサブミットしません。
因みに、"return false"がないと、ポップアップが出ますが、次のページに進んでしまいます。
上記JSは以下の方法でもOK
$(function(){
  $("#addToCart").on('click', function(e){
    if(!(document.getElementById('quantity').value)){
      alert("数量を選択してください。");
      return false;
    }else{
      return true;
    }
  })
});