Avir94 Avir94 - 2 months ago 11
CoffeeScript Question

jQuery show method not working in rails app

(jQuery/Javascript newbie here)

Within my rails app, I am trying to see if the selected option in a dropdown menu matches the text "New Category", and if so, then I want a piece of html to show a new line for the the form where the user can specify a new category name.

In my class.coffee file I have this:

$(document).on "turbolinks:load", ->
if( $('#category-select option.selected').text() == "New Category")
$('#new-categrory').show()


In my class.html.erb file I have this:

<div class="col-xs-6 center block">
<%= f.label :category, "Category" %>
<%= f.select :category, options_for_select(getAllCategories), {}, {:required => true, :class => 'form-control', id: "category-select"} %>
<%= f.text_field :category, :class => 'form-control', id: "new-category" %>
</div>


(where my getAllCategories function just returns an array of options, but that's not important)

and lastly I have a class rule in my class.scss:

#new-category{
display: none;
}


So I'm pretty stuck. I've tried using syntax from multiple stackoverflow question's and nothing is working yet.

I have been able to run a simple alert popup when the dropdown is selected, so I know jQuery is running.

Any help would be appreciated.

Answer

I figured out how to do it.

I ran it once the '#select-category' id got changed, so

$(document).on "turbolinks:load", ->
    $('#category-select').change ->
        selected = $('#category-select').val()
        if selected is "New Category"
            $('#new-category').show()
        else
            $('#new-category').hide()

And that finally did the trick. Hope that helps anyone else running into this problem.