Summary of tips (Rails) that you can use all the way because you understand that it is jQuery discount

I'm making a web app with Rails. The experience value of Ruby on Rails is about one year in September. I've come to be able to create various functions, so I'll summarize them a little. How do you make such a function? Please comment if there is something like. think.

What is jQuery?

Official: [https://jquery.com/:title]

If you look at this article, I don't think it's necessary, but I quoted it from Wikipedia.

jQuery is a JavaScript library designed to make it easier to write JavaScript code for web browsers. John Resig released it at BarCamp NYC in January 2006. It is used in various situations, and some call it the de facto standard for JavaScript libraries [2]. The catch phrase below the logo is "write less, do more" (meaning "do more with less description").
Source: [https://ja.wikipedia.org/wiki/JQuery:title]

How to use relatively

You can get the DOM element with jquery, manipulate the DOM element by the action at that time, add or remove the class, and perform asynchronous processing with ajax. (I think people will come up with "What is a DOM element?" And ask "What is a DOM element?")
For example, ↓
[https://watablogtravel.com/document-object-model/:title]

 $(document).on('change', '[name^="company[purchases_attributes]["][name$="][product_code]"]', function(){
    var supplier_product_code = $(this).nearest('[name^="company[purchases_attributes]"][name$="[supplier_product_code]"]');

    $.ajax({
      url: '/suppliers/purchases/get_supplier_product_code',
      type: "GET",
      dataType: "json",
      headers: { 'X-CSRF-Token': token },
      data: { "product_code": $(this).val(), "supplier_product_code": supplier_product_code.val() },
      success: function (data) {
        supplier_product_code.val(data.supplier_product_code);
        supplier_product_code.trigger('change');
      },
      error: function () {
        supplier_product_code.val("");
        supplier_product_code.trigger('change');
      }
    });
  })

In this part of the 1st and 2nd lines, I personally found it convenient to get the DOM element with prefix match, suffix match, and "and" (&&) condition.
By writing like the second line, the name starts with company [purchases_attributes] and the name ends with [supplier_product_code]

$(this).nearest('[name^="company[purchases_attributes]"][name$="[supplier_product_code]"]');

The prefix match and the suffix match are used at the same time.

So, for example, name ^ =" company [purchases_attributes] [123456] [supplier_product_code] , etc., parts such as 123456 can be acquired together even with dynamically changing elements such as id.
In addition, you can use nearest to get the closest matching DOM element to the one you got.
A frequently used usage is to change the status of the checked items on the list screen at once with ajax. Something like that.
Batch operation of list screen is easier with ajax than with form. </ b>

There was a very easy-to-understand table, so I will quote it.

[name] Get the element of name attribute
[name=value] Gets the attribute whose value is the value named name. Perfect matching
[name^=value] Get the attribute whose value named name starts with value. Prefix match
[name$=value] Get an attribute whose value named name ends with value. Backward match
[name*=value] Get an attribute that has the string value in the value named name. Partial Match
[name~=value] Gets an attribute where the values named name are separated by spaces and one is value.
[name|=value] Get an attribute where the values named name are separated by a hyphen and one is value

Source: [https://code-schools.com/javascript-dom-match/:title]

Pass JSON from Ruby controller to javascript side.

I knew that ajax could pass variables from JS to Ruby, but couldn't it be the other way around?
If you think that, you can do it after all.

manner: Write reder json: in controller and return json data to javascript side.

def get_supplier_product_code 
      if params.key?(:product_code)
        params[:supplier_product_code] = Product.find_by(code: params[:product_code]).supplier_product_code
      end
      render json: {supplier_product_code: params[:supplier_product_code]}.to_json
    end

render json: {supplier_product_code: params[:supplier_product_code]}.to_json JSON data can be returned to the ajax communication side by writing.

How to get JSON

$.ajax({
      url: '/suppliers/purchases/get_supplier_product_code',
      type: "GET",
      dataType: "json",
      headers: { 'X-CSRF-Token': token },
      data: { "product_code": $(this).val(), "supplier_product_code": supplier_product_code.val() },
      success: function (data) {
        supplier_product_code.val(data.supplier_product_code);
        supplier_product_code.trigger('change');
      },
      error: function () {
        supplier_product_code.val("");
        supplier_product_code.trigger('change');
      }
    });

As I wrote above, you can get the JSON variable by doing data.supplier_product_code after success.
After that, you can rewrite the data on the JS side and Ruby on Rails side as you like.

that's all.

Recommended Posts

Summary of tips (Rails) that you can use all the way because you understand that it is jQuery discount
Basics of jQuery that even freeters can understand
When is it said that you can use try with a Swift error?
The first thing to do before you can use Rails6 Ajax
[Rails + Webpacker] I want to use images of assets! Until you can view the image in Vue.js
Incident (rails) that is logged out when user editing of the application
To you who lament that the conversion of JODConverter + LibreOffice is slow