Search code examples
coffeescriptmodal-dialogmaterializeruby-on-rails-5

Dropdown on change open a modal with data


I have a Vendor dropdown in my rails app. I am trying to fetch some data using ajax and currently the returned data is simply displayed in a div on the same page.

I am wondering if it is possible to pass the vendor id to the modal and it then display add the records associated with the vendor after making the ajax call?

here is my current coffeescript code to retrieve the data and display in the div.

$ ->
if $('body.bills.new').length > 0
    $('body.bills.new #bill_vendor_id').change ->
        $.ajax
            url: '/purchase_orders/?vendor_id='+ $('body.bills.new #bill_vendor_id option:selected').val()
            success: (data) ->
                alert data
                $('#data').html data

Solution

  • Of course it is!

    You can for example add the class of the dropdown you want to show in the #bill_vendor_id data.

    For example:

    <input type="text" id="bill_vendor_id" data-dropdown-class="something" ... />
    

    And in the js you find the class and use it to hit the dropdown:

    ...
     $.ajax
        url: '/purchase_orders/?vendor_id='+ $('body.bills.new #bill_vendor_id option:selected').val()
          success: (data) ->
            div_class = $(this).data('dropdown-class')
            $('.' + div_class).html data
    

    EDIT

    Okay. Yes, it depends. Do you want to change all the html or append some html? You can either use .html data or .append data

    And remember to show the modal, if you're not already doing this.