"Trouble with jQuery: Selecting an image to change isn't

Can someone help me figure out why my simple image change on a dropdown isn't working correctly?

You can find the code on this Jsfiddle.

Thank you for any assistance!

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $("option").attr("imagePath"));
    event.preventDefault();
});

<img src="http://placehold.it/100/0000FF/000000" name="preview" /><br /><br />

<select class="form-control" name="display_avatar" id="display_avatar">
    <option value="1" imagePath="http://placehold.it/100/cccccc/000000">First</option>
    <option value="2"imagePath="http://placehold.it/100/ghghgh/000000">Second</option>
    <option value="3"imagePath="http://placehold.it/100/5fgrty/000000">Third</option>
    <option value="4"imagePath="http://placehold.it/100/ff0000/000000">Fourth</option>
</select>

Answer №1

If you want to retrieve the value from the first option only, use this code:

$("option").attr("imagePath")

For an alternative method, try the following code snippet instead:

this.selectedOptions[0].getAttribute("imagePath")

You can view the updated demonstration here: http://jsfiddle.net/979vbv0j/2/

Answer №2

$("option") retrieves all option elements on the current page. In order to achieve your desired outcome, you should implement the following code:

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $(this).find("option:selected").attr("imagePath"));
    event.preventDefault();
});

For further reference, visit: jQuery Get Selected Option From Dropdown

Update: View a working example here - http://jsfiddle.net/vm6zjobj/1/

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

Tips for stopping a page from reloading when a link is clicked

I have implemented a script to enable AJAX on my blogger site using the jQuery Ajaxify plugin (https://github.com/swook/jquery-ajaxify-plugin). This allows users to listen to music via the player without experiencing interruptions while navigating through ...

Refining Flask-Generated Table Content with jQuery Filters

I'm currently attempting to render a Jinja2 template that showcases an HTML table and enables dynamic filtering to search through the table content. Unfortunately, I'm facing issues with getting the search functionality to work properly. While th ...

Tips for successfully passing the event in a jQuery function

I currently have four buttons on my HTML page. Create Airport Create City Create City Shortname Create Airport Shortname All of these buttons will trigger an AJAX call to the same page. Here is a snippet of the code for one of the buttons: $('#im ...

What is the best method for flipping the sequence of elements in media queries?

I am facing an issue with two divs, left and right, on my webpage. When the screen size is less than 500px, I want the left div to move to the bottom and the right div to move to the top. Essentially, I need to swap the positions of these divs in the DOM. ...

Real-time searching on Laravel using AJAX technology

I'm having trouble with implementing a live search feature in my Laravel 5.4 project. The console is showing an error message: GET http://localhost/bodegasilusion/public/search 500 (Internal Server Error) jquery.js:9392 Despite trying different solut ...

Tips for traversing through jquery ui accordion when a single panel has been disabled

I currently have a jQuery UI accordion set up with Next and Previous buttons in each panel to navigate through the sections. Additionally, I have a select HTML element in one of the panels where I can choose an option. If Option 1 is selected, the second a ...

Tips for ensuring that jQuery runs in the correct order within Angular 2

As a beginner with Angular 2 and asynchronous loading, I have encountered some difficulties in finding the right approach for running jQuery scripts in the correct sequence within an Angular 2 project. Despite exploring various resources such as: How to u ...

Steps to design a text div that extends beyond the bottom boundaries

Can anyone help me troubleshoot this design code using Bootstrap 3.x? Specifically, I am facing an issue with the following div. Any suggestions? Click here for more information. img{max-width:100%;} .mydiv{margin-bottom:20px;} .mytext{ positio ...

Having trouble with your CSS dropdown menu?

I've been struggling to implement a dropdown menu on my website following an online tutorial. Despite following the steps, I can't seem to get it working. It's frustrating because I want to move on to backend development. Hoping someone can ...

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Several treeviews for selecting data

I need some help with a specific assignment. The back end code is all set, but I'm struggling with the UI component. The task requires two tree views, one on the left and one on the right. The left tree view will contain states with multiple children, ...

Issue with loading a link within a tab on jQuery UI Tabs

I'm encountering an issue with jQuery UI tabs. Specifically, I have tabs that are loaded using ajax and my problem is that I want to load page links within the page but am struggling to do so. Below is the code of my page with the tabs: <script&g ...

Having issues with object-fit: cover not functioning properly in Safari browser

Encountering a browser support issue at the moment. Everything is functioning as expected on Firefox and Chrome, but Safari is causing problems with images. Currently, the image size is set using "object-fit: cover" and working properly on Chrome/Firefox. ...

Encountering a 500 server error when using jQuery AJAX for a GET request

Check out the flask python code here: Also, take a look at the html+js in the index.html template: An issue arises where everything runs smoothly on the local Flask server but encounters a 500 error when attempting to search after deployment with Apache ...

Ways to adjust the size of an HTML fieldset?

Is there a way to decrease the space between the paragraph and the border of this fieldset? I attempted to adjust the margins in the following manner: fieldset { margin: 1px; margin-top: 2px; border-top-right-radius: 1px; } <fieldset> < ...

The model property consistently receives a false value from a checkbox, even when it is checked. The data is retrieved in JSON format from an

After submitting a form, the following code will be triggered: $.ajax({ url: '/Company/CheckError', type: 'POST', data: JSON.stringify($(this).serializeObject()), dataType: 'json', proc ...

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

Is it possible to determine which child element is currently in view within a scrollable parent div?

In an attempt to replicate a "current page" feature using divs, similar to a PDF reader. document.addEventListener("DOMContentLoaded", function(event) { var container = document.getElementById("container"); container.onscroll = function() { let ...

Apply a red border to any form inputs that contain incorrect information when the submit

How can I add red borders to my form inputs only when they are invalid after submission, without displaying the red borders from the start? Currently, I am using the input:invalid selectors in CSS, but this causes the red borders to appear immediately. I ...

Utilizing JavaScript Files Instead of NPM as a Library for Open Layers: A Step-by-Step Guide

I've been attempting to get Open Layers to function in my Eclipse web development environment, but I've encountered some challenges along the way. The setup instructions provided on the Open Layers website focus mainly on using npm. Nevertheless, ...