Search code examples
jqueryruby-on-railsselectionchanged

onchange display/change a partial


There is a drop down using select

<%= select("array", "folder", @rows.keys, {}, :onchange =>"?" )%>

There is a partial called "form"

<%= render "form"%>

I need to render the partial whenever there is a change in the selection. Please, let me know if there is a way to do it. I found that the remote_function is deprecated from rails 3.0. I have seen all possible links here with onchange and select tags but could not find a proper answer. I'm new to rails, jQuery and Ajax. Please help

Thanks


Solution

  • why not render the form in the same page and hide and show it on change of select tag

    <html> 
      <body>
    
      <!-- Your Select tag -->
      <select id="select_id"> 
        <option value="one" selected> One </option>
        <option value="two"> Two </option>
      </select>
    
      <!-- Here your a div inside with your form is placed -->
      <div id="myform" style="display:none">
        <form action="/someurl">
          .. ..
        </form> 
    
       <!-- JQuery code to  show the form -->
      <script type="text/javascript">
        $(document).ready(function() {
           $("select#select_id").bind("change",function() {
             if ($(this).val() == "one") 
              $("div#myform").show(); 
             else
              $("div#myform").hide(); 
           })
       })
    
      </script>
    
    </html>
    

    I you still want to make an ajax request I pretty simple too

    $(document).ready(function() {
      $("select#select_id").bind("change",function() {
        if ($(this).val() == "one") {
         $.ajax({
            url : "/form_url",
            data : "html", 
            type: "GET",
            success : function(data) {
              $("div#myform").html(data)
            }
         }) 
    
      })
    })
    

    on the server side you need to respond_to the ajax request using format.js and render a template directed using render command or just define a .js.erb file