Consider the following code from one of the view files:
<table>
<tr>
<th><%= f.label(:shop, "Shop:") %></th>
<td><%= select_with_new_option(f, :shop, :name, :id) %></td>
</tr>
...
</table>
select_with_new_option
is my helper method that is defined in app/helpers/application_helper.rb
. It generates a select box, containing all shops in this case, and in addition "Create new shop" option.
I would like to add a Javascript code that will display:
<div>
<label for="new_shop">New shop:</label>
<input id="new_shop" name="new_shop" type="text" />
</div>
once the "Create new shop" option is selected.
Is that possible to generate this Java开发者_运维百科script code from select_with_new_option
, or I should do this in other way ?
Since I can't see your generated code, I am just making this up, but you'll have to fine tune to suit your needs... (this also assumes you're using jQuery, modify as needed).
Assuming your output looks something like like:
table code and such
<select id="shop_select">
<option value="new">New Shop</option>
<!-- other options -->
</select>
somewhere on the page lives your div
<div id="new_shop_holder" style="display: none;">
<label for="new_shop">New shop:</label>
<input id="new_shop" name="new_shop" type="text" />
</div>
<script type="text/javascript">
$(function(){
var $new_shop_holder = $('#new_shop_holder');
$('select#shop_select').change(function(e) {
if (this.value == 'new') { $new_shop_holder.show(); }
else { $new_shop_holder.hide(); }
});
});
</script>
You can try
<%= select('shop', 'name', get_shop_name, {:include_blank => "Create"}, :onchange => "show_new_form();") %>
where show_new_form is the javascript for hiding and displaying your new shop holder div or you can use
<%= select('shop', 'name', get_shop_name, {:include_blank => "Select"}, :onchange => "new Ajax.Updater('options', 'action_url', {asynchronous:true, evalScripts:true, parameters:value})") %>
and an action in your controller
def action_url
render :update { |page| page.replace_html "new_shop_holder", :partial => 'add_new_shop' } if value == ""
end
This will call the partial having the form to enter new shop only if create a shop is selected.
精彩评论