Skip to content

Instantly share code, notes, and snippets.

@rockkhuya
Created February 5, 2014 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rockkhuya/8816088 to your computer and use it in GitHub Desktop.
Save rockkhuya/8816088 to your computer and use it in GitHub Desktop.
Use Jquery to add dynamic field and edit value before submit
$(function(){
$("a[shp-action=add_field_need_things]").click( function(){
var num = $("ul[shp-role=dynamic_field_need_things]").length + 1;
var new_element = [];
new_element.push(
'<ul class="inline nested-fields" shp-role="dynamic_field_need_things" id="', num, '">',
'<li>',
'<input class="input-mini" id="', num, '" name="need_things" shp-role="dynamic_field_need_things" type="text" />',
'</li>\n',
'<li><a id="', num, '" shp-role="delete_field_need_things">×</a> </li>',
'</ul>'
);
$("div[shp-role=append_field_need_things]").append(new_element.join(''));
});
$("a[shp-role=delete_field_need_things]").click( function(){
$(this).parent().parent().remove();
});
$("input[shp-action=submit_tour]").click(function(){
var need_things = [];
$("input[shp-role=dynamic_field_need_things]").each(function(){
need_things.push( $(this).val() );
});
$("#tour_need_things").val(need_things.join("\n"));
$(this).submit();
});
});
<div class="controls">
<%= render "need_things", need_things: @tour.need_things %>
<%= f.hidden_field :need_things %>
</div>
<div shp-role="append_field_need_things">
<% extract_line(@tour.need_things).each_with_index do |thing, id| %>
<ul class="inline nested-fields" shp-role="dynamic_field_need_things" id="1">
<li>
<%= text_field_tag :need_things, thing, id: id, class: ['input-mini'], "shp-role" => "dynamic_field_need_things" %>
</li>
<li><a id="<%= id %>" shp-role="delete_field_need_things">×</a></li>
</ul>
<% end %>
</div>
<p><a shp-action="add_field_need_things">+追加</a></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment