Displaying Image Previews in Rails View Using JavaScript

I am working on a functionality where I have a text_field that contains the URL of an image. The goal is to load this URL into an img tag and update the preview image when the user changes the URL in the text field.

Below is the relevant erb code 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="">

Additionally, here is the embedded JavaScript code:

<script type="text/javascript">

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

});

However, upon loading the page, the preview image does not display anything and the source URL doesn't change as expected.

Answer №1

It is important to provide the selector of the object you want to locate. Additionally, utilizing document ready is recommended.

$(document).ready(function() {
  $('#preview').attr('src', $('#image_url').text());
  $('#image_url').on("focusout", function(){
    $('#preview').attr('src', $(this).text());
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating with UI-Router within a single view for both viewing and editing purposes

I have been encountering an issue with changing states between the view page and edit page using UI-Router. Here are some of the things I have attempted: Controller: $stateProvider .state('showViewA', { views: { ...

The error message states that the element (0 , _dayjs.Dayjs) is not a valid function

I am currently in the process of replacing momentjs with dayjs. To start, I included the necessary dependencies: "dayjs":"1.10.7" Next, I imported dayjs like this: import { Dayjs } from 'dayjs'; To retrieve the start of the ...

Determine the HTTP status code for a request using Vue.js and Ajax

I need to retrieve the HTTP status code after submitting a form (using the form submission function): return fetch(serviceUrl + 'Collect', { method: "POST", headers: new Headers({ "Content-Type": "application/json", Authoriza ...

The issue arises with the Google Map marker failing to function correctly when pulling data

I've recently started learning Google Maps. It's interesting that markers work and are displayed when statically declared, but not when retrieved from a database. // var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.69 ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Challenges with server side JavaScript in Nuxt.js, causing confusion with the framework

My partner and I are embarking on a website project for our school assignment, and we have opted to utilize Vue.js and Nuxt.js as the front-end frameworks, along with Vuesax as our chosen UI Framework. Despite our lack of experience with these tools and we ...

Tips for updating the display by fetching data from a database through a websocket

I am looking for a solution to update a specific part of my webpage without having to refresh the entire content. On my index.html page, I have three panels displaying various ticket statuses. I want to automatically update the number of resolved tickets s ...

Using Symfony 4.3 to submit a form via Ajax and store data in a database

As a beginner in the world of Ajax, I am currently trying to use Ajax to submit a register form with Symfony but seem to be facing some challenges in understanding the process: Within my Controller: /** * @Route("/inscription", name="security_re ...

Using the Ruby on Rails link_to tag along with a mouseenter jQuery function allows for dynamic

How can I make an image display in a div when the mouse hovers over a link_to using Rails? The code below seems to work, but I'm unsure of how it functions. <a href="#" class="nav-link roll"> <%= image_tag("chair1.jpg") %>Chesterfield Cha ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

"Eliminating Redundant JS and CSS Files in Magento to Improve

While analyzing the performance of a website, I noticed that GTmetrix found some CSS & JS files being loaded from different locations but containing the same file. An example: <action method="addItem" module="ves_blockbuilder" ifconfig="ves_blockbuilde ...

Utilizing Angular: Filtering Views Based on JSON Data Values

I am struggling to figure out why a basic Angular filter is not working for me in this example. Despite following the recommended format I found online, it does not seem to be functioning properly. Essentially, I just need to display information from the a ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

Jquery form calculation not matching up

I've been struggling to make this jQuery math function work with my form. The snippet works fine, but when I try to integrate it into the actual form, I can't seem to get it aligned properly to perform the required calculations. Any suggestions ...

Updating Angular JS views in real-time using database changes

I am currently in the process of building a social networking application using AngularJS. I have come across an issue regarding data binding. In my app, there is a timeline div where all the recent posts are displayed, along with a status updater at the t ...

Using Bootstrap, jQuery, and PHP to dynamically load input fields in a modal window

I am looking to dynamically load input fields in a modal window using PHP. While researching, I came across suggestions to utilize AJAX for this purpose. However, I have limited knowledge about AJAX. The plan is as follows: 1) When the user clicks on the ...

What is the best way to efficiently pass a prop from a Parent styled component to its children's styled components, regardless of how deeply nested they are?

I am utilizing these customized components: import styled, { css } from 'styled-components' const Container = styled.div` background-color: ${props => props.theme === "light" ? "hsl(0, 0%, 98%)" : "hsl(235, 24%, 19% ...

Sending values to server-side function with JavaScript

Is there a way to invoke a code-behind function from JavaScript and pass parameters to it? For instance: <script> var name; <% createUser(name) %> </script> private void createUser(string Name) { // Do some complex operations } I&a ...

The response header does not contain a valid JWT token

Here's a function I've implemented to authenticate users by creating a response header: function verifyUser(res, id) { const payload = { id } const token = jwt.sign(payload, config.JWT_KEY, { expiresIn: '24h' ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...