Change images with mouse click image and pass image id to form to be submitted with form
I have a form for a user 开发者_如何转开发to create a message, leave their name, email(optional) and I want them to click some buttons ('<<' '>>' for example) to change an image icon for their message and I want to be able to pass the name of the image to the controller with the form to be able to load it into the table for the message.
This is part of the form:
<% form_tag('/greeting/new') do %>
<fieldset>
<legend><%= @legend %></legend>
<%=error_messages_for "user" %>
<%=error_messages_for "greeting" %>
<div class="form_row">
<%= text_field :greeting, :header, :size =>
Greeting::FORM_HEADER_FIELD_SIZE,
:maxlength => Greeting::HEADER_MAX_LENGTH %>
</div>
...
<div id="icon_box">
<label for="icon">Select Icon for your Message</label>
<a href="#" onclick="changeMySrc(1)"> >> </a><img id="Img1" src="/images/icon/icon1.jpg" />
Inside the layout for the message I have the following: (I would like to be able to do this for many images but don't know how with rails)
<script type='text/javascript'>
function changeMySrc(i) {
if(i==1){
document.getElementById("Img1").src="/images/icons/<%=@icons[1].image_tag %>";
}
else if (i==2)
{
document.getElementById("Img1").src="/images/icons/<%=@icons[0].image_tag %>";
}
}
</script>
The icon names are kept in a database (@icons.image_tag) as I want to be able to categorize the images and the images are kept in a folder on the server.
I want to preload the images as they are small and there are not too many. Or maybe some better technique.
I just can't find anything on the web that can do this combined with rails.
Can anyone point me in the right direction?
Much appreciated.
You can use a hidden field in the form and change its value in the javascript along with the image source
form
<%= text_field :greeting, :header, :size =>
Greeting::FORM_HEADER_FIELD_SIZE,
:maxlength => Greeting::HEADER_MAX_LENGTH %>
<%= hidden_field :greeting, :image_name %>
javascript
if(i==1){
document.getElementById("Img1").src="/images/icons/<%=@icons[1].image_tag %>";
document.getElementById("greeting_image_name").value= "<%=@icons[1].image_tag %>";
}
else if (i==2)
{
document.getElementById("Img1").src="/images/icons/<%=@icons[0].image_tag %>";
document.getElementById("greeting_image_name").value= "<%=@icons[0].image_tag %>";
}
}
精彩评论