how to populate select box depending upon the selection of the radio button on rails

anyone knows what will be the possible ajax and rails script for populating dropdown list values based on selected radio button on rails 3 example there are two type of platform choices(windows, unix) of radio button then when you clicked the unix radio button, the dropdown listbox will filter only the unix type something(patch).

The idea is the dropdown has a contents already from the database (<%= f.select :other_platform, Patch.all.map {|p| ["#{p.patch_type} #{p.number}: #{p.summary}", p.id ] }, {:include_blank => true} %>) then I need to do is to "filter" only the values that has a windows type example base on the radio button that has been selected if you clicked the windows type then the dropdown menu will show only the windows type of patches and hide the unix type or the list that has a unix word on it like regx(checking the query)and if you choose or clicked the unix then only the unix type will appear at the dropdown menu

thanks please answer

Dani AI

Generated

Two practical ways to solve this (both valid — choice depends on dataset size and UX):

Client-side filtering (fast, simplest when the select is reasonably small). Render every option once and add a data attribute with the patch type. Attach a single change handler to the radio group and show/hide option elements that do not match the chosen type. This avoids round-trips and keeps the UI snappy — good for tens or a few hundred options. As noted, JavaScript handles the change event; unlike the XHR example he gave, this keeps everything in the browser.

Example jQuery-style change handler (illustrates the idea; adapt selectors to your form):

$(document).on('change', 'input[name="your_model[patch_type]"]', function(){
  var chosen = $(this).val();
  $('#your_select_id option').each(function(){
    var keep = $(this).data('patch-type') === chosen || $(this).val() === '';
    $(this).toggle(keep);
  });
});

Server-side filtering (recommended when the full list is large or must reflect server rules). On radio change send a small AJAX request to a Rails action that returns option tags (HTML partial) or JSON. Replace the select contents on success. This keeps filtering authoritative (no client assumptions) and supports pagination or search if needed. In Rails 3 prefer unobtrusive handlers (jquery-ujs or plain $.get/$.ajax) and respond with a partial that renders only the option elements.

Troubleshooting and cautions: match the model attribute (patch_type) instead of regexing labels; ensure option data values and radio values use the same normalization (case); keep an empty/placeholder option; verify rails-ujs or jQuery is loaded and watch the browser console for errors; when results are empty, disable or show a helpful message in the select. — either route will work; pick client-side for simplicity, server-side for scale and accuracy.

Recommended Answers

All 5 Replies

What you need to do is to create an Ajax link similar to to send the selection to the server. Then in your controller, retrieve data and render a partial which will become the response to the client. In the partial, you can render whatever you like (a form as you gave in your post).

Thanks for the idea but can you give me a sample so that i can figure out atleast, I'm new here on rubyonrails.

here are my radio_buttons in _form.erb

<%= f.radio_button :patch_type, 'unix' %> <%= f.label :patch_type_unix, "Unix" %><br/>
<%= f.radio_button :patch_type, 'windows' %> <%= f.label :patch_type_windows, "Windows" %>

then i'm rendering the page like this:

<div id ="cor_patches">
        <%= render :partial => 'other_patch', :locals => {:f => f} %>
</div>

then in the _other_patch.html.erb

<h2>Corresponding Patches</h2>
<table class="patchtable tableau">
<tr>
    <td><strong><%= f.label :Other_Platform %></strong></td>
    <td>

    <%=  f.select :other_platform, Patch.all.map {|p| ["#{p.patch_type} #{p.number}: #{p.summary}", p.id ] }, {:include_blank => true} %>

    </td>
</tr>
</table>

should i need to use onclick on the radio buttons?
how can i make ajax? can you add additional codes for this.
thanks

Oh, I didn't read your post carefully. The approach I told you would not work in your case because you are using radio button. You may go to for a better suggestion. The way I deal with radio button and Ajax is to call a JavaScript function to do the work - verify the value selected and retrieve the data to view.

// in javascript (may be in an external file but needs to be included in the main view
function ajscriptcall(actionURL, displayDivId) {
  // verify what is selected and call ajax here
}

// in view
<%= f.radio_button :patch_type, 'unix', 
    :onchange=>"ajscriptcall('ajax_method_in_controller_name')" %>
<%= f.label :patch_type_unix, "Unix" %>
<br/>
<%= f.radio_button :patch_type, 'windows', 
    :onchange=>"ajscriptcall('ajax_method_in_controller_name')" %>
<%= f.label :patch_type_windows, "Windows" %>

Oh, I didn't read your post carefully. The approach I told you would not work in your case because you are using radio button. You may go to for a better suggestion. The way I deal with radio button and Ajax is to call a JavaScript function to do the work - verify the value selected and retrieve the data to view.

// in javascript (may be in an external file but needs to be included in the main view
function ajscriptcall(actionURL, displayDivId) {
  // verify what is selected and call ajax here
}

// in view
<%= f.radio_button :patch_type, 'unix', 
    :onchange=>"ajscriptcall('ajax_method_in_controller_name')" %>
<%= f.label :patch_type_unix, "Unix" %>
<br/>
<%= f.radio_button :patch_type, 'windows', 
    :onchange=>"ajscriptcall('ajax_method_in_controller_name')" %>
<%= f.label :patch_type_windows, "Windows" %>

thanks Taywin

but what kind of ajax do i have to do? can you give me an example through this? thanks again i got an idea.. but i need an ajax codes hehe i'm also kind of new in ajax,.. thanks

OK, here it is. It is not very pretty by the way. ;)

# controller
  def ajax_test_radio
    objs = AClass.find(:all, :conditions=>["something=:v", {:v=>params[:radval]}])
    render :partial => "display_radio_options",
           :locals => { :objs=>objs }
  end

# partial _display_radio_options.rhtml
<%
# :objs  - an array of objects to be displayed as 'option' on this page
objs.each do |obj|
%>
<option value=<%=obj.value%>><%=obj.value%></option>
<% end %>

# the view which calls ajax
<script type="text/javascript">
function populateSelect(radio, targetID) {
  var xml = getXMLObject()
  if (xml) {
    var url = ""+radio.value
    xml.onreadystatechange = function() {
      // only if xml is "loaded"
      if (xml.readyState == 4) {
        var el = document.getElementById(targetID)
        // only if "OK"
        if ((xml.status == 200) && (el!=null)) {
          el.innerHTML = xml.responseText;  // can use responseXML but need some tweak
        }
        else {
          el.innerHTML = "Error. Cannot retrieve data properly"
        }
      }
    };
    xml.open("GET", url, true);
    xml.send(null);
  }
}

function getXMLObject() {  // the XML is the Ajax (Asynchronous Javascript and XML)
  var req
  if (window.XMLHttpRequest) { // native XMLHttpRequest object
    req = new XMLHttpRequest()
  }
  else if (window.ActiveXObject) { // IE/Windows ActiveX version
    req = new ActiveXObject("Microsoft.XMLHTTP")
  }
  else if (document.all) {  // IE 9
    req = new XMLHTTPRequest()
  }
  return req
}
</script>

<% form_for @bc, :url=>"test_radio" do |f| %>
  <%= f.radio_button :code, 'a%', :onchange=>"populateSelect(this, 'sel_form')" %> <%= f.label :code_a, "Code A" %><br/>
  <%= f.radio_button :code, 'b%', :onchange=>"populateSelect(this, 'sel_form')" %> <%= f.label :code_b, "Code B" %>
  <select id="sel_form" name="sel_form"></select>
<% end %>

If you are going to use Ajax from 'link_to', I believe that you need to add <%= javascript_include_tag "prototype" %> line at the top of the view page. If you create your own XML object using JavaScript as above, you may not need the include tag.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.