Image Preview in Rails View with JS

Go To StackoverFlow.com

0

I have a text_field that is the url of an image and I want to load that into and img tag. I also want to update the image when the image_url text box loses focus so they can change the url and see the preview.

Here is the pertinent erb for the view:

 <div class="control-group">
    <%= f.label :image, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_field :image_url, :class => 'text_field', id: "image_url" %>
    </div>
  </div>

  Preview: <img id="preview" src="">

and the embedded js...

<script type="text/javascript">

document.observe('dom:loaded', function() {
  $('preview').src = $('image_url').text
  $('image_url').bind("focusout",function(){
    $('preview').src = this.text
    )}

});

On load I get nothing and the src doesn't change

2012-04-04 20:08
by Chris


3

You need to specify the selector of the object you are trying to find. Also I would use document ready.

$(document).ready(function() {
  $('#preview').src = $('#image_url').text();
  $('#image_url').bind("focusout",function(){
    $('#preview').src = this.text();
  });
});
2012-04-04 20:14
by Mike Silvis
By "specify the selector of the object", Mike means that your id selectors are missing a # in front of i - Juan Mendes 2012-04-04 20:22
Ads